? ? ? 今天在項目中遇到一個數據庫查詢的問題:三張表分別放置不同的東西:分享的音頻相關數據、分享的文字圖片說說、分享的主題相關數據。所有分享的東西都可看做新鮮事,現在要求從這三張表將相同的幾個字段的數據全部查找出來按照發布時間先后排序(至于為什么不把這三張表的數據整到一張表里面這是由于數據庫是這樣設計的,咱這先不討論數據庫設計的好壞,就記錄一下自己怎么使用三表聯合查詢將這三張表的數據都查找出來)。
在網上找了些聯合查詢相關的資料:
有幾個不錯的技術博客做了很好的介紹:
1、http://blog.sina.com.cn/s/blog_6ad62438010168lg.html
2、http://www.ynpxrz.com/n598810c2024.aspx
介紹:使用union或union all都可實現合并兩個或多個select語句的結果集:其中union會將查出來的結果中相同內容的行合并,而union all不會合并相同行。
要點:
(1)兩次或多次查詢的列數必須一致;
(2)以第一個子查詢語句中列的類型為標準,之后所有查詢語句中各列的類型第一個子查詢中對應類的類型一致;
(3)多次select語句中查詢的列名可以不相同,最后查詢結果表的列名是以第一個子查詢語句中的列名來命名的;
(4)如果子句中有order by,limit,需要用括號()包起來。如果將order by,limit放到所有子句之后,即對最終合并的結果表進行排序或篩選。
操作:
1、參考上面給出的兩個技術博文,我自己進行了實踐,前面幾次都出錯,我下面給出我敲出來的sql已經相應的報錯內容,并附上截圖:
sql語句1: mysql> select * from (select alarm_publishSite,alarm_publishtime from alarm union select theme_issueLocation,theme_publishtime from theme);
報錯:ERROR 1248 (42000): Every derived table must have its own alias
這個錯誤是指每個派生表需要一個別名
sql語句2:mysql> select * from (select alarm_publishSite,alarm_publishtime from alarm) as?t1 union (select theme_issueLocation,theme_publishtime from theme) as t2;
報錯:ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that?corresponds to your MySQL server version for the right syntax to use near 'as t2' at line 1
sql語句3:mysql> select * from (select alarm_publishSite,alarm_publishtime from alarm) as?t1 union (select theme_issueLocation,theme_publishtime from theme);
這次很幸運,成功將兩個表中的數據聯合查出來了,如下圖:
sql2語句與sql3語句之間的區別你可以比較得出。
sql語句4:mysql> select * from (select alarm_publishSite,alarm_publishtime from alarm) as?t1 union (select theme_issueLocation,theme_publishtime from theme) as t2 union (select subject_issueLocation,subject_time from subject);
報錯:ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that?corresponds to your MySQL server version for the right syntax to use near 'as t2?union (select subject_issueLocation,subject_time from subject)' at line 1
這個報錯是指 ”as t2?union (select subject_issueLocation,subject_time from subject)“這部分附近有語法問題。
sql語句5:mysql> select * from (select alarm_publishSite,alarm_publishtime from alarm) as?t1 union (select theme_issueLocation,theme_publishtime from theme) union (select subject_issueLocation,subject_time from subject);
得出結果,如下圖:
sql4語句與sql5語句之間的區別你可以比較得出。
sql語句6:mysql> select * from (select alarm_publishSite as location,alarm_publishtime as?time from alarm) as t1 union (select theme_issueLocation,theme_publishtime from?theme) union (select subject_issueLocation,subject_time from subject) order by?time desc;
得出查詢結果,如下圖:
在sql6語句中,主要就是給第一個子查詢中查詢的列名去了相應的別名,最后可以看到,查詢出來的結果表中的字段名就成了剛取的別名了。