SQL RIGHT JOIN

RIGHT JOIN返回右表中的所有行,即使左表中没有匹配项也不会影响右表中的结果。这意味着如果 ON 子句匹配左表中的 0 条记录;仍将在结果中返回一行,但在左表的每一列中都为 NULL。

这意味着 RIGHT JOIN 返回右表中的所有值,加上左表中匹配的值,或者在没有匹配项的情况下返回 NULL。

语法

RIGHT JOIN的基本语法如下。

SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;

示例

现在我们看如下的两张表

1. CUSTOMERS 表

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

2. ORDERS 表

+-----+---------------------+-------------+--------+
|OID  | DATE                | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 |           3 |   3000 |
| 100 | 2009-10-08 00:00:00 |           3 |   1500 |
| 101 | 2009-11-20 00:00:00 |           2 |   1560 |
| 103 | 2008-05-20 00:00:00 |           4 |   2060 |
+-----+---------------------+-------------+--------+

现在,让我们使用 RIGHT JOIN 连接这两个表,如下所示。

SQL> SELECT  ID, NAME, AMOUNT, DATE
   FROM CUSTOMERS
   RIGHT JOIN ORDERS
   ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

结果如下

+------+----------+--------+---------------------+
| ID   | NAME     | AMOUNT | DATE                |
+------+----------+--------+---------------------+
|    3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
|    3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
|    2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
|    4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
+------+----------+--------+---------------------+

但是这里我们看到并没有左表字段为NULL的行,所以我们再给ORDERS表加一条记录

INSERT INTO ORDERS VALUES (104,'2008-05-21 00:00:00',9,2160);

我们新加的这条记录的CUSTOMER_ID的值在 CUSTOMERS 表中并不存在,现在我们再使用 RIGHT JOIN语句进行查询,看一下什么结果

SQL> SELECT  ID, NAME, AMOUNT, DATE
   FROM CUSTOMERS
   RIGHT JOIN ORDERS
   ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

结果如下

+------+----------+--------+---------------------+
| ID   | NAME     | AMOUNT | DATE                |
+------+----------+--------+---------------------+
|    3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
|    3 | kaushik  |   1560 | 2009-11-20 00:00:00 |
|    3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
|    4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
| NULL | NULL     |   2160 | 2008-05-21 00:00:00 |
+------+----------+--------+---------------------+

示例图

RIGHT-JOIN-查询左表出现NULL

现在我们看左表出现了NULL的情况。

查看笔记

扫码一下
查看教程更方便