萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> mysql LEFT JOIN多表聯結查詢

mysql LEFT JOIN多表聯結查詢

在mysql中如果要同時查找多表並且多表時間有關系查詢我們有很多種方法來實現,現在我們只介紹利用mysql LEFT JOIN來實現。

具體操作

MySQL支持Select和某些Update和Delete情況下的Join語法,具體語法上的細節有:
 table_references:
    table_reference [, table_reference] …
 table_reference:
    table_factor
  | join_table
 table_factor:
    tbl_name [[AS] alias]
        [{USE|IGNORE|FORCE} INDEX (key_list)]
  | ( table_references )
  | { OJ table_reference LEFT OUTER JOIN table_reference
        ON conditional_expr }
 join_table:
    table_reference [INNER | CROSS] JOIN table_factor [join_condition]
  | table_reference STRAIGHT_JOIN table_factor
  | table_reference STRAIGHT_JOIN table_factor ON condition
  | table_reference LEFT [OUTER] JOIN table_reference join_condition
  | table_reference NATURAL [LEFT [OUTER]] JOIN table_factor
  | table_reference RIGHT [OUTER] JOIN table_reference join_condition
  | table_reference NATURAL [RIGHT [OUTER]] JOIN table_factor
 join_condition:
    ON conditional_expr | USING (column_list)

除了常用的兩個表連接之外,SQL(MySQL) JOIN 語法還支持多表連接。多表連接基本語法如下:

... FROM table1 INNER|LEFT|RIGHT JOIN table2 ON condition INNER|LEFT|RIGHT JOIN table3 ON condition ...

JOIN 多表連接實現了從多個表中獲取相關數據,下面是三個原始數據表:

article 文章表: aid title content uid tid 1 文章1 文章1正文內容... 1 1 2 文章2 文章2正文內容... 1 2 3 文章3 文章3正文內容... 2 1 5 文章5 文章5正文內容... 4 1 user 用戶表: uid username email 1 admin [email protected] 2 小明 [email protected] 3 Jack [email protected] type 文章類型表: tid typename 1 普通文章 2 精華文章 3 草稿

 代碼如下 復制代碼

SELECT * FROM t1 LEFT JOIN (t2, t3, t4) ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)

copyright © 萬盛學電腦網 all rights reserved