浅谈mysql中多表不关联查询的实现方法

2017-01-03 14:26:30  mysql多表关联查询

大家在使用MySQL查询时正常是直接一个表的查询,要不然也就是多表的关联查询,使用到了左联结(left join)、右联结(right join)、内联结(inner join)、外联结(outer join)。这种都是两个表之间有一定关联,也就是我们常常说的有一个外键对应关系,可以使用到 a.id = b.aId这种语句去写的关系了。这种是大家常常使用的,可是有时候我们会需要去同时查询两个或者是多个表的时候,这些表又是没有互相关联的,比如要查user表和user_history表中的某一些数据,这个时候就是所谓的不关联查询了。

这时候用的是union   all语句。比如:

</pre> <pre class="html" name="code">(select name,sex,age from user where name like '王%' ) union   all (select name,sex,age from user_history where name like '王%' ) ;

这个语句是用来查询用户表以及历史表中所有王姓的人员的信息。这个同样是可以进行排序、截取操作的,

(select name,sex,age from user where name like '王%' ) union   all (select name,sex,age from user_history where name like '王%' ) order by age desc limit 0,50;

这个就是取得这两个表中按年龄排序前50的人员了。

以上就是小编为大家带来的浅谈mysql中多表不关联查询的实现方法全部内容了,希望大家多多支持~

浅谈mysql中多表不关联查询的实现方法》阅读地址:http://www.haoshilao.net/13624/

最新图文教程: