SQL RIGHT JOIN关键字
该RIGHT JOIN关键字返回右表(表2)的所有行,在左表(表1)匹配的行。 其结果是在左侧空时不存在匹配。
SQL RIGHT JOIN语法
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name ;
要么:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name = table2.column_name ;
PS! 在某些数据库中RIGHT JOIN称为RIGHT OUTER JOIN。
演示数据库
在本教程中,我们将使用众所周知的Northwind示例数据库。
下面是从选择"Orders"表:
订单ID | 客户ID | 员工ID | 订购日期 | ShipperID |
---|---|---|---|---|
10308 | 2 | 7 | 1996-09-18 | 3 |
10309 | 37 | 3 | 1996-09-19 | 1 |
10310 | 77 | 8 | 1996-09-20 | 2 |
而从选择"Employees"表:
员工ID | 姓 | 名字 | 生日 | 照片 | 笔记 |
---|---|---|---|---|---|
1 | Davolio | Nancy | 12/8/1968 | EmpID1.pic | Education includes a BA in psychology..... |
2 | Fuller | Andrew | 2/19/1952 | EmpID2.pic | Andrew received his BTS commercial and.... |
3 | Leverling | Janet | 8/30/1963 | EmpID3.pic | Janet has a BS degree in chemistry.... |
SQL RIGHT JOIN例
下面的SQL语句将返回所有雇员,他们任何一笔订单:
例
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN
Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY
Orders.OrderID;
试一试»
注:RIGHT JOIN关键字返回所有来自右表(雇员)中的行,即使在左表(订单)不匹配。