聯合查詢 子查詢

distinct 去除重複記錄. 重複的記錄,指的是字段值都相同的記錄,而不是部分字段相同的記錄

       例: select distinct days from teacher_class;

union 聯合查詢  將多跳select語句的結果合併到一起,稱之爲聯合操作。

       例:(select t_name,days from teacher_class where c_name='php0115' order by days desc linit 1) union (select t_name,days from teacher_class where c_name='php0225' order by days desc limit1)

場景:獲得數據的條件,出現邏輯衝突,或者很難在一個邏輯內表示,就可以拆分成多個邏輯分別實現,最後將結果合併到一起。

如果union的結果存在重複的記錄,那麼會消除重複,可以通過選項all達到目的。

排序:

子語句結果的排序:

1 將子語句包裹子括號內

2 子語句的order by 只有在order by 配合limit時才生效,原因是:union在做子語句時,會對沒有limit子句的order by 優化。

子查詢

 場景:查詢代課天數最多的那個老師的信息

       例:select t_name,gender from teacher_class order by days limit 1.

 先獲得最多的代課天數是多少天,在判斷哪個老師的代課天數和最大值是一樣的

 var1=select max(days) from teacher_class.

  select t_name,gender from teacher_class where days=var1;

也就是 select t_name,gender from teacher_class where days=(select max(days) from teacher_class);


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