SQL INNER JOIN(內部連接)
最頻繁使用的和重要的聯接是INNER JOIN。它也被稱爲一個等值連接。
INNER JOIN通過結合基於聯接謂詞兩個表(表1和表2)列值創建一個新的結果表。查詢比較表1中的每一行與表2中的每一行,找到所有滿足聯接謂詞的行。 當聯接謂詞被滿足時,對於每個匹配的一對A和B的列值被組合成一個結果行。
語法
INNER JOIN基本語法如下:
SELECT table1.column1, table2.column2... FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
例子:
考慮下面的兩個表中,(a)CUSTOMERS表如下:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
(b) 另一個ORDERS表命令如下:
+-----+---------------------+-------------+--------+ | OID | DATE | ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+
現在,讓我們使用INNER JOIN這兩個表如下:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
這將產生以下結果:
+----+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +----+----------+--------+---------------------+ | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | +----+----------+--------+---------------------+