SQL INNER JOIN
语句根据公共列连接两个表,并选择这些列中具有匹配值的行。
示例
-- join Customers and Orders tables with their matching fields customer_id
SELECT Customers.customer_id, Orders.item
FROM Customers
INNER JOIN Orders
ON Customers.customer_id = Orders.customer_id;
这里,SQL 命令连接了 Customers 和 Orders 表。
结果包括 customer_id(来自 Customers)和 item(来自 Orders),其中客户 ID 匹配(Customer.customer_id = Orders.customer_id
)。
SQL INNER JOIN 语法
SELECT columns_from_both_tables
FROM table1
INNER JOIN table2
ON table1.column1 = table2.column2
这里,
- table1 和 table2 - 两个要连接的表
- column1 和 column2 - table1 和 table2 中共有的列
示例 1:SQL INNER JOIN
-- join the Customers and Orders tables
-- with customer_id and customer fields
SELECT Customers.customer_id, Customers.first_name, Orders.amount
FROM Customers
INNER JOIN Orders
ON Customers.customer_id = Orders.customer;
这里,如果 customer_id(Customers 表的)和 customer(Orders 表的)的值匹配,SQL 命令将从两个表中选择指定的行。

如您所见,INNER JOIN
排除了两个表之间不共有的所有行。
注意: 我们也可以使用 SQL JOIN 而不是 INNER JOIN
。基本上,这两个子句是相同的。
示例 2:使用匹配字段连接两个表
-- join Categories and Products tables
-- with their matching fields cat_id
SELECT Categories.cat_name, Products.prod_title
FROM Categories
INNER JOIN Products
ON Categories.cat_id = Products.cat_id;
这里,SQL 命令使用匹配字段 cat_id 选择 Categories 和 Products 表之间的公共行。
结果集包含 Categories 中的 cat_name 列和 Products 中的 prod_title 列。
更多关于 SQL INNER JOIN
我们也可以使用 INNER JOIN
连接两个以上的表。例如:
-- join three tables: Customers, Orders, and Shippings
SELECT C.customer_id, C.first_name, O.amount, S.status
FROM Customers AS C
INNER JOIN Orders AS O
ON C.customer_id = O.customer
INNER JOIN Shippings AS S
ON C.customer_id = S.customer;
这里,SQL 命令
- 根据 customer_id(来自 Customers 表)和 customer(来自 Orders 表)连接 Customers 和 Orders 表
- 并根据 customer_id(来自 Customers 表)和 customer(来自 Shippings 表)连接 Customers 和 Shippings 表
该命令返回在两个连接条件中列值都匹配的行。
注意:要运行此命令,每个单独的表都必须有一个 customer_id 列。列名可以不同,只要它们具有相同的数据即可。
这是一个带有 WHERE 子句 的 INNER JOIN
示例
-- join Customers and Orders table
-- with customer_id and customer fields
SELECT Customers.customer_id, Customers.first_name, Orders.amount
FROM Customers
INNER JOIN Orders
ON Customers.customer_id = Orders.customer
WHERE Orders.amount >= 500;
这里,SQL 命令连接两个表并选择 amount 大于或等于 500 的行。
另请阅读