MySQL-inner join、left join、right join区别

创建实验环境

create database test;

use test;

create table ta (aid int(1),aname(5));

insert into ta values('1','1001');
insert into ta values('2','1002');
insert into ta values('3','1003');
insert into ta values('4','1004');
insert into ta values('5','1005');

create table tb (bid int(2),bname(5));

insert into tb values('1','2001');
insert into tb values('2','2002');
insert into tb values('3','2003');
insert into tb values('4','2004');
insert into tb values('8','2005');

查看两表

select * from ta;
+------+-------+
| aid  | aname |
+------+-------+
|    1 |  1001 |
|    2 |  1002 |
|    3 |  1003 |
|    4 |  1004 |
|    5 |  1005 |
+------+-------+

select * from tb;
+------+-------+
| bid  | bname |
+------+-------+
|    1 |  2001 |
|    2 |  2002 |
|    3 |  2003 |
|    4 |  2004 |
|    8 |  2005 |
+------+-------+

left join(左连接)

select * from ta left join tb on ta.aid=tb.bid;

+------+-------+------+-------+
| aid  | aname | bid  | bname |
+------+-------+------+-------+
|    1 |  1001 |    1 |  2001 |
|    2 |  1002 |    2 |  2002 |
|    3 |  1003 |    3 |  2003 |
|    4 |  1004 |    4 |  2004 |
|    5 |  1005 | NULL |  NULL |
+------+-------+------+-------+

left join将A表(ta)作为基准表与B表进行匹配,匹配的条件是A表中的aid等于B表中的bid(ta,aid=tb.bid),所以可以看到在B表中找不到bid=5的行,所以B表中对应的行,为NULL


right join(右连接)

select * from ta right join tb on ta.aid=tb.bid;

+------+-------+------+-------+
| aid  | aname | bid  | bname |
+------+-------+------+-------+
|    1 |  1001 |    1 |  2001 |
|    2 |  1002 |    2 |  2002 |
|    3 |  1003 |    3 |  2003 |
|    4 |  1004 |    4 |  2004 |
| NULL |  NULL |    8 |  2005 |
+------+-------+------+-------+

与left join相反,right join使用的是右边的B表作为基准,在A表中没有找到aid=8的行,所有这里为NULL


inner join(内连接)

select * from ta inner join tb on ta.aid=tb.bid;

+------+-------+------+-------+
| aid  | aname | bid  | bname |
+------+-------+------+-------+
|    1 |  1001 |    1 |  2001 |
|    2 |  1002 |    2 |  2002 |
|    3 |  1003 |    3 |  2003 |
|    4 |  1004 |    4 |  2004 |
+------+-------+------+-------+

在inner join中,不以任何一表为基准,只显示双方都有的行,A表与B表中都有id1,2,3,4但对方没有5和8

你可能感兴趣的:(MySQL,mysql,join,inner,join,left,join,right,join)