目录
[一、内连接(INNER JOIN)](#一、内连接(INNER JOIN))
[二、外连接(LEFT JOIN、RIGHT JOIN 和 FULL JOIN)](#二、外连接(LEFT JOIN、RIGHT JOIN 和 FULL JOIN))
[三、交叉连接(CROSS JOIN)](#三、交叉连接(CROSS JOIN))
在 MySQL 中,常见的连接查询有四种:内连接(INNER JOIN)、外连接(LEFT JOIN、RIGHT JOIN 和 FULL JOIN)、交叉连接(CROSS JOIN)和自连接。以下是对每种连接查询的详细介绍。
一、内连接(INNER JOIN)
-
内连接是最常用的连接类型之一,它返回两个表中符合连接条件的行。如果两个表中的行没有匹配的值,则不会包含在结果集中。
-
语法:
SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column;
-
示例:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
二、外连接(LEFT JOIN、RIGHT JOIN 和 FULL JOIN)
-
外连接用于返回左表(左侧表)的所有行,以及与右表(右侧表)匹配的行。如果右表中没有匹配的行,则会用 NULL 值填充。
-
LEFT JOIN:返回左表的所有行以及右表中符合条件的行。
-
RIGHT JOIN:返回右表的所有行以及左表中符合条件的行。
-
FULL JOIN:返回左表和右表的所有行,如果某行在一个表中没有匹配,则用 NULL 值填充。
-
语法:
SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;
SELECT * FROM table1 FULL JOIN table2 ON table1.column = table2.column; -
示例:
-- LEFT JOIN
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;-- RIGHT JOIN
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
RIGHT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;-- FULL JOIN
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
三、交叉连接(CROSS JOIN)
-
交叉连接返回两个表的笛卡尔积,即两个表中所有可能的组合。
-
语法:
SELECT * FROM table1 CROSS JOIN table2;
-
示例:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
CROSS JOIN Orders;
四、自连接
-
自连接是指在同一个表内进行连接操作,通常用于在表中查找相关联的信息。
-
语法:
SELECT a.column1, b.column2
FROM table AS a, table AS b
WHERE a.column = b.column; -
示例:
SELECT e1.EmployeeName AS Employee, e2.EmployeeName AS Manager
FROM Employees AS e1, Employees AS e2
WHERE e1.ManagerID = e2.EmployeeID;