SQL INNER JOIN
INNER JOIN
INNER JOIN
關鍵字會選擇兩個表中都具有匹配值的記錄。
讓我們看看 Products 表的一部分
ProductID | ProductName | CategoryID | Price |
---|---|---|---|
1 | Chais | 1 | 18 |
2 | Chang | 1 | 19 |
3 | Aniseed Syrup | 2 | 10 |
以及 Categories 表的一部分
CategoryID | CategoryName | 描述 |
---|---|---|
1 | Beverages | Soft drinks, coffees, teas, beers, and ales |
2 | Condiments | Sweet and savory sauces, relishes, spreads, and seasonings |
3 | Confections | Desserts, candies, and sweet breads |
我們將透過兩個表中的 CategoryID
欄位,將 Products 表與 Categories 表連線起來。
示例
使用 INNER JOIN 關鍵字連線 Products 和 Categories 表
SELECT ProductID, ProductName, CategoryName
FROM Products
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID;
自己動手試一試 »
注意: INNER JOIN
關鍵字只返回兩個表中都有匹配的行。這意味著,如果您有一個沒有 CategoryID 的產品,或者有一個 CategoryID 不存在於 Categories 表中的產品,那麼該記錄將不會在結果中返回。
語法
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
命名列
在 SQL 語句中指定列時,包含表名是一個好習慣。
示例
指定表名
SELECT Products.ProductID, Products.ProductName, Categories.CategoryName
FROM Products
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID;
自己動手試一試 »
上面的例子在不指定表名的情況下也可以工作,因為指定的列名都不存在於兩個表中。如果您嘗試在 SELECT
語句中包含 CategoryID
,而沒有指定表名,您將收到一個錯誤(因為 CategoryID
存在於兩個表中)。
JOIN 或 INNER JOIN
JOIN
和 INNER JOIN
會返回相同的結果。
INNER
是 JOIN
的預設連線型別,所以當您寫 JOIN
時,解析器實際上會將其寫為 INNER JOIN
。
示例
JOIN 等同於 INNER JOIN
SELECT Products.ProductID, Products.ProductName, Categories.CategoryName
FROM Products
JOIN Categories ON Products.CategoryID = Categories.CategoryID;
自己動手試一試 »
連線三個表
以下 SQL 語句選擇包含客戶和發貨人資訊的訂單。
這是 Shippers 表
ShipperID | ShipperName | Phone |
---|---|---|
1 | Speedy Express | (503) 555-9831 |
2 | United Package | (503) 555-3199 |
3 | Federal Shipping | (503) 555-9931 |
示例
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
自己動手試一試 »