1. 程式人生 > 其它 >資料庫之join用法

資料庫之join用法

  • JOIN: 如果表中有至少一個匹配,則返回行
  • LEFT JOIN: 即使右表中沒有匹配,也從左表返回所有的行
  • RIGHT JOIN: 即使左表中沒有匹配,也從右表返回所有的行
  • FULL JOIN: 只要其中一個表中存在匹配,就返回行

join 用於根據兩個或多個表中的列之間的關係,從這些表中查詢資料。

ELECT a.c_port_code,b.c_ass_code
FROM T_D_AC_TRADE_IVT a
INNER JOIN T_P_AB_PORT b
ON a.c_port_code = b.c_port_code
ORDER BY b.c_ass_code

LEFT JOIN 關鍵字會從左表 (table_name1) 那裡返回所有的行,即使在右表 (table_name2) 中沒有匹配的行。


SELECT a.c_port_code, b.c_ass_code
FROM T_D_AC_TRADE_IVT a
LEFT JOIN T_P_AB_PORT b
ON a.c_port_code = b.c_port_code
ORDER BY b.c_ass_code

RIGHT JOIN 關鍵字會右表 (table_name2) 那裡返回所有的行,即使在左表 (table_name1) 中沒有匹配的行。

SELECT a.c_port_code, b.c_ass_code
FROM T_D_AC_TRADE_IVT a
RIGHT JOIN T_P_AB_PORT b
ON a.c_port_code = b.c_port_code
ORDER BY b.c_ass_code

FULL JOIN

只要其中某個表存在匹配,FULL JOIN 關鍵字就會返回行。

SELECT a.c_port_code, b.c_ass_code
FROM T_D_AC_TRADE_IVT a
FULL JOIN T_P_AB_PORT b
ON a.c_port_code = b.c_port_code
ORDER BY b.c_ass_code