mysql中UNION進行多表查詢的注意事項

來源:互聯網
上載者:User


假設有兩個欄位完全一致的表,table1和table2。欄位分別為password, username, email。
則使用UNION(或UNION ALL)進行多表查詢的基本方法就是簡單的串連:

 SELECT password,username,email
 FROM
 table1
 where username like '123'
 
 UNION ALL //或用UNION以去除重複資料
 
 SELECT password,username,email
 FROM
 table2
 where username like '123'

但是,如果表與表的欄位不同,有重疊卻不完全一致。就不是簡單地用UNION來串連即可了。
要UNION兩個或多個表,必須滿足的條件就是這些表的欄位都一樣。為了滿足這個條件,可以用","來代替缺少的欄位。
例如:table1中有欄位password,username,email,ip;table2中有欄位password,username。則查詢方法如下:

 
   /**
    * mysql union
    * coder: xiaohudie
    * Jan 2015
    */

 SELECT password,username,email,ip
 FROM
 table1
 where username like '123'
 
 UNION ALL
 
 SELECT password,username,',',',' 
 FROM
 table2
 where username like '123'
以此類推。

--
PS: 抱歉各位,我撤下了評論回複郵件通知的功能,望周知。
因為SMTP外掛程式在資料庫中留下郵箱密碼造成了一定危險。至於為什麼會造成危險,咳咳,那就要問問我某位親密無間的好朋友了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.