當我們使用MySQL進行關系型數據庫查詢時,經常會用到連接操作。其中最常用的連接方式為外連接(outer join),而左連接(left join)則是外連接的一種。在左連接中,將左表的所有數據都保留,同時匹配右表中相應的數據,如果右表中沒有匹配的數據,那么結果集中將會出現NULL值。這意味著左連接可能會產生一些多余的數據,本文將通過實例演示說明這一點。
-- 創建兩張表 CREATE TABLE Orders ( OrderID int NOT NULL PRIMARY KEY, CustomerID int NOT NULL, OrderDate date ); CREATE TABLE Customers ( CustomerID int NOT NULL PRIMARY KEY, CustomerName char(50), ContactName char(50), Country char(50) ); -- 插入一些數據 INSERT INTO Customers (CustomerID, CustomerName, ContactName, Country) VALUES (1, 'Alfreds Futterkiste', 'Maria Anders', 'Germany'); INSERT INTO Customers (CustomerID, CustomerName, ContactName, Country) VALUES (2, 'Ana Trujillo Emparedados', 'Ana Trujillo', 'Mexico'); INSERT INTO Customers (CustomerID, CustomerName, ContactName, Country) VALUES (3, 'Antonio Moreno Taquería', 'Antonio Moreno', 'Mexico'); INSERT INTO Customers (CustomerID, CustomerName, ContactName, Country) VALUES (4, 'Around the Horn', 'Thomas Hardy', 'UK'); INSERT INTO Customers (CustomerID, CustomerName, ContactName, Country) VALUES (5, 'Berglunds snabbk?p', 'Christina Berglund', 'Sweden'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (1, 3, '2021-01-01'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (2, 4, '2021-01-02'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (3, 2, '2021-01-03'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (4, 4, '2021-01-04'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (5, 1, '2021-01-05'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (6, 5, '2021-01-06'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (7, 2, '2021-01-07'); INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES (8, 1, '2021-01-08'); -- 使用左連接查詢 SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
上述示例中,我們創建了兩張表Orders和Customers,并向其中插入了一些數據。然后,我們使用左連接查詢了兩張表中的數據,結果如下圖所示:
+------------------------+---------+ | CustomerName | OrderID| +------------------------+---------+ | Alfreds Futterkiste | 5 | | Alfreds Futterkiste | 8 | | Ana Trujillo Emparedados| 3 | | Ana Trujillo Emparedados| 7 | | Antonio Moreno Taquería| 1 | | Around the Horn | 2 | | Around the Horn | 4 | | Berglunds snabbk?p | 6 | +------------------------+---------+
可以看到,左連接返回了Customers表中的所有數據,而Orders表中沒有匹配的數據,相應的位置則使用了NULL值填充。例如,Ana Trujillo Emparedados在Orders表中只有一條數據,但在左連接的結果集中,她的CustomerName被重復出現了兩次。這便是左連接可能產生的多余數據。需要注意的是,如果需要進行一些數據清洗或者去除多余的數據,我們可以通過應用其他條件或函數來實現。
上一篇css畫布三角形粗細
下一篇mysql左連接子查詢