它与LEFT连接类似,除了表的处理方式相反。使用RIGHT联接,右表中的每一行都将出现在结果集中。对于右表中没有左表中匹配行的行,左表中的列将显示NULL。为了理解它,我们以两个名为tbl_1和tbl_2的表为例,它们具有以下数据-
mysql> Select * from tbl_1; +----+--------+ | Id | Name | +----+--------+ | 1 | Gaurav | | 2 | Rahul | | 3 | Raman | | 4 | Aarav | +----+--------+ 4 rows in set (0.00 sec) mysql> Select * from tbl_2; +----+---------+ | Id | Name | +----+---------+ | A | Aarav | | B | Mohan | | C | Jai | | D | Harshit | +----+---------+ 4 rows in set (0.00 sec)
现在,对RIGHT JOIN的查询可以如下所示:
mysql> SELECT tbl_1.id,tbl_2.id FROM tbl_1 RIGHT JOIN tbl_2 ON tbl_1.name = tbl_2.name; +------+----+ | id | id | +------+----+ | 4 | A | | NULL | B | | NULL | C | | NULL | D | +------+----+ 4 rows in set (0.00 sec)