資料庫-mysql資料連線

來源:互聯網
上載者:User

標籤:.com   alt   沒有   多表查詢   個數   images   icon   src   adb   

一:Mysql 串連的使用

在前幾章節中,我們已經學會了如果在一張表中讀取資料,這是相對簡單的,但是在真正的應用中經常需要從多個資料表中讀取資料。

本章節我們將向大家介紹如何使用 MySQL 的 JOIN 在兩個或多個表中查詢資料。

你可以在 SELECT, UPDATE 和 DELETE 語句中使用 Mysql 的 JOIN 來聯合多表查詢。

JOIN 按照功能大致分為如下三類:

  • INNER JOIN(內串連,或等值串連):擷取兩個表中欄位匹配關係的記錄。
  • LEFT JOIN(左串連):擷取左表所有記錄,即使右表沒有對應匹配的記錄。
  • RIGHT JOIN(右串連): 與 LEFT JOIN 相反,用於擷取右表所有記錄,即使左表沒有對應匹配的記錄。
  • full join 全串連  兩個表並集,mysql並沒有直接支援,而是通過unicon實現
二:內串連

  兩個表的交集

  

MariaDB [test2]> select * from a;+------+| name |+------+|    1 ||    2 ||    3 ||    4 |+------+4 rows in set (0.00 sec)MariaDB [test2]> select * from b;+------+| name |+------+|    3 ||    4 ||    5 ||    6 |+------+4 rows in set (0.00 sec)MariaDB [test2]> select * from a inner join b on a.name=b.name;+------+------+| name | name |+------+------+|    3 |    3 ||    4 |    4 |+------+------+2 rows in set (0.00 sec)MariaDB [test2]> select * from a,b where a.name=b.name;+------+------+| name | name |+------+------+|    3 |    3 ||    4 |    4 |+------+------+2 rows in set (0.00 sec)
三:LEFT JOIN

MySQL left join 與 join 有所不同。 MySQL LEFT JOIN 會讀取左邊資料表的全部資料,即便右邊表無對應資料。

MariaDB [test2]> select * from a left join b on a.name=b.name;+------+------+| name | name |+------+------+|    3 |    3 ||    4 |    4 ||    1 | NULL ||    2 | NULL |+------+------+4 rows in set (0.00 sec)
四: RIGHT JOIN

MySQL RIGHT JOIN 會讀取右邊資料表的全部資料,即便左邊邊表無對應資料。

MariaDB [test2]> select * from a right join b on a.name=b.name;+------+------+| name | name |+------+------+|    3 |    3 ||    4 |    4 || NULL |    5 || NULL |    6 |+------+------+4 rows in set (0.00 sec)

 

五:full join 

  兩個表的並集

  

MariaDB [test2]> select * from a left join b on a.name =b.name union select * from a right join b on a.name =b.name;+------+------+| name | name |+------+------+|    3 |    3 ||    4 |    4 ||    1 | NULL ||    2 | NULL || NULL |    5 || NULL |    6 |+------+------+6 rows in set (0.00 sec)

 

資料庫-mysql資料連線

聯繫我們

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