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


 


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