MySQL(16):Select-union(聯集查詢)

來源:互聯網
上載者:User

標籤:

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(聯集查詢)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.