標籤:
1. Select-union(聯集查詢)
union用於把來自許多SELECT語句的結果組合到一個結果集合中。
用法:
SELECT ...UNION [ALL | DISTINCT]SELECT ...[UNION [ALL | DISTINCT]SELECT ...]
2. 引入Select-union(聯集查詢)的案例:
(1)首先查詢出所有teacher_class列中所有的記錄,如下:
(2)按照欄位t_name和days,查詢出所有帶過php0115班的老師,如下:
(3)在上面(2)查詢出來的結果基礎上,按照days進行排序檢索,如下:
(4)在(3)查詢結果的基礎上,檢索出days最大的記錄,如下:
(5)如果我們想查詢出php0228班的授課天數(days最大)老師記錄,就需要上面查詢命令的班級號就行了,如下:
select t_name,days from teacher_class where c_name=‘php0228‘ order by days desc limit 1;
如此一來,如果資料庫內容很多,我們可能要重複很多這樣的商務邏輯,該怎麼最佳化呢?
3. Select-union(聯集查詢)的案例:
Select-union(聯集查詢):把多條select語句的結果,合并在一起。
使用uinion關鍵字,聯合兩個select語句即可。
現在說明我們的需求:獲得2個班代課最後的老師。
語句1:select t_name,days from teacher_class where c_name=‘php0115‘ order by days desc limit 1;
語句2:select t_name,days from teacher_class where c_name=‘php0228‘ order by days desc limit 1;
使用union關鍵字聯合上面兩個select語句即可。
(1)語句1 和 語句2,查詢結果如下:
(2)使用union關鍵字聯合上面兩個select語句,如下:
(select t_name,days from teacher_class where c_name=‘php0115‘ order by days desc limit 1)union(
select t_name,days from teacher_class where c_name=‘php0228‘ order by days desc limit 1
);
MySQL(16):Select-union(聯集查詢)