SQL INNER JOIN:内连接

 
INNER JOIN 是 SQL 中最重要、最常用的表连接形式,只有当连接的两个或者多个表中都存在满足条件的记录时,才返回行。

SQL INNER JOIN 子句将 table1 和 table2 中的每一条记录进行比较,以找到满足条件的所有记录,然后将每一对满足条件的记录的字段值,合并为一条新的结果行。

INNER JOIN 是默认的表连接方式。当不加任何修饰性的关键字,只写 JOIN 时,默认就是 INNER JOIN 连接。

语法

INNER JOIN 的基本语法如下:
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_column1 = table2.common_column2;
table1.common_column1 = table2.common_column2 是连接条件,只有满足此条件的记录才会合并为一行。

以上 SQL 语句将产生 table1 和 table2 的交集,只有 table1 和 table2 中匹配的行才被返回,如下图所示:

SQL INNER JOIN

示例

现在有如下所示的两个表,分别是客户表和订单表。

表1: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 |
+----+----------+-----+-----------+----------+

表2:ORDERS 表
+-----+---------------------+-------------+--------+
| OID | DATE                | CUSTOMER_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 |
+----+----------+--------+---------------------+

如果您不希望选取表的所有记录,也可以加上 WHERE 子句,如下所示:
SQL> SELECT  ID, NAME, AMOUNT, DATE
     FROM CUSTOMERS
     INNER JOIN ORDERS
     ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
     WHERE AMOUNT >1515
     ORDER BY AMOUNT;
执行结果:
+----+----------+--------+---------------------+
| ID | NAME     | AMOUNT | DATE                |
+----+----------+--------+---------------------+
|  2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
|  4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
|  3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
+----+----------+--------+---------------------+