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的人员了。


 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章