當(dāng)我們使用MySQL進(jìn)行關(guān)系型數(shù)據(jù)庫查詢時(shí),經(jīng)常會(huì)用到連接操作。其中最常用的連接方式為外連接(outer join),而左連接(left join)則是外連接的一種。在左連接中,將左表的所有數(shù)據(jù)都保留,同時(shí)匹配右表中相應(yīng)的數(shù)據(jù),如果右表中沒有匹配的數(shù)據(jù),那么結(jié)果集中將會(huì)出現(xiàn)NULL值。這意味著左連接可能會(huì)產(chǎn)生一些多余的數(shù)據(jù),本文將通過實(shí)例演示說明這一點(diǎn)。
-- 創(chuàng)建兩張表 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) ); -- 插入一些數(shù)據(jù) 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;
上述示例中,我們創(chuàng)建了兩張表Orders和Customers,并向其中插入了一些數(shù)據(jù)。然后,我們使用左連接查詢了兩張表中的數(shù)據(jù),結(jié)果如下圖所示:
+------------------------+---------+ | 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表中的所有數(shù)據(jù),而Orders表中沒有匹配的數(shù)據(jù),相應(yīng)的位置則使用了NULL值填充。例如,Ana Trujillo Emparedados在Orders表中只有一條數(shù)據(jù),但在左連接的結(jié)果集中,她的CustomerName被重復(fù)出現(xiàn)了兩次。這便是左連接可能產(chǎn)生的多余數(shù)據(jù)。需要注意的是,如果需要進(jìn)行一些數(shù)據(jù)清洗或者去除多余的數(shù)據(jù),我們可以通過應(yīng)用其他條件或函數(shù)來實(shí)現(xiàn)。