摘要:在本教程中,您将学习如何使用 MySQL RIGHT JOIN
查询两个表中的数据。
MySQL RIGHT JOIN 子句简介
MySQL RIGHT JOIN
与LEFT JOIN ,
只是连接表的处理相反。
以下是两个表t1
和t2
的RIGHT JOIN
语法:
SELECT
select_list
FROM t1
RIGHT JOIN t2 ON
join_condition;
Code language: SQL (Structured Query Language) (sql)
在这个语法中:
t1
是左表,t2
是右表。-
join_condition
指定匹配两个表中的行的规则。
如果join_condition
使用等于运算符 ( =
) 并且两个表的连接列具有相同的名称,则可以使用如下所示的USING
语法:
SELECT
select_list
FROM t1
RIGHT JOIN t2 USING(column_name);
Code language: SQL (Structured Query Language) (sql)
因此,以下连接条件是等效的:
ON t1.column_name = t2.column_name
Code language: SQL (Structured Query Language) (sql)
和
USING (column_name);
Code language: SQL (Structured Query Language) (sql)
RIGHT JOIN
如何运作。
RIGHT JOIN
开始从右表中选择数据 ( t2
)。它将右表中的每一行与左表中的每一行相匹配。如果这两行都导致连接条件计算为TRUE
,则RIGHT JOIN
将这些行的列组合成一个新行,并将该新行包含在结果集中。
如果右表中的行没有左表中的匹配行,则RIGHT JOIN
将右表中的行的列与右表中所有列的NULL
值组合成一个新行,并将该行包含在结果中放。
换句话说, RIGHT JOIN
返回右表中的所有行,无论左表中是否有匹配的行。
需要强调的是, RIGHT JOIN
和LEFT JOIN
子句在功能上是等效的,只要表顺序相反,它们就可以相互替换。
请注意, RIGHT OUTER JOIN
是RIGHT JOIN
的同义词。因此,您可以互换使用它们。
MySQL RIGHT JOIN 子句示例
我们将使用示例数据库中的employees
和customers
表进行演示:

customers
表中的salesRepEmployeeNumber
列链接到employees
表中的employeeNumber
列。
销售代表或员工可能负责零个或多个客户。每个客户都由零或一名销售代表负责。
如果salesRepEmployeeNumber
列中的值为 NULL,则表示该客户没有任何销售代表。
1) 简单的 MySQL RIGHT JOIN 示例
该语句使用RIGHT JOIN
子句将customers
表与employees
表连接起来。
SELECT
employeeNumber,
customerNumber
FROM
customers
RIGHT JOIN employees
ON salesRepEmployeeNumber = employeeNumber
ORDER BY
employeeNumber;
Code language: SQL (Structured Query Language) (sql)

在这个例子中:
RIGHT JOIN
返回employees
表中的所有行,无论employees
表中的行在customers
表的salesRepEmployeeNumber
列中是否具有匹配的值。- 如果
employees
表中的行与customers
表中没有匹配的行,则RIGHT JOIN
对customerNumber
列使用NULL
。
2)使用MySQL右连接
查找不匹配的行
以下语句使用RIGHT JOIN
子句查找不负责任何客户的员工:
SELECT
employeeNumber,
customerNumber
FROM
customers
RIGHT JOIN employees ON
salesRepEmployeeNumber = employeeNumber
WHERE customerNumber is NULL
ORDER BY employeeNumber;
Code language: SQL (Structured Query Language) (sql)

概括
- MySQL
RIGHT JOIN
允许您从两个或多个相关表中查询数据。 -
RIGHT JOIN
开始从右表中选择行。无论左表中是否有匹配行,它总是从右表返回行。 -
RIGHT OUTER JOIN
是RIGHT JOIN
的同义词。