create table tb_user_age (
id bigint auto_increment comment 'ID' primary key,
age int null comment '年龄'
)
comment = '用户年龄' engine = innodb charset utf8mb4;
create table tb_user_name (
id bigint auto_increment comment 'ID' primary key,
name varchar(30) null comment '姓名'
)
comment = '用户姓名' engine = innodb charset utf8mb4;
insert into tb_user_age (age) values (10),(11),(12),(13);
insert into tb_user_name (id,name) values (2,'zhang'),(3,'li'),(4,'zhou'),(5,'chen');
内连接 (join 或 inner join)
select a.*, b.* from tb_user_age a
inner join tb_user_name b
on a.id = b.id
# a.id age b.id name
# 2 11 2 zhang
# 3 12 3 li
# 4 13 4 zhou
title
这种场景下得到的是满足某一条件的A,B内部的数据;正因为得到的是内部共有数据,所以连接方式称为内连接。
外连接
左连接 (left join 或left outer join)
右连接 (right join 或right outer join)与左连接类似
select a.*, b.* from tb_user_age a
left join tb_user_name b
on a.id = b.id
# a.id age b.id name
# 2 11 2 zhang
# 3 12 3 li
# 4 13 4 zhou
# 1 10 <null> <null>
title
这种场景下得到的是A的所有数据,和满足某一条件的B的数据;
全连接 (mysql不支持,左连接 union 右连接)
select a.*, b.* from tb_user_age a
left join tb_user_name b on a.id = b.id
union
select a.*, b.* from tb_user_age a
right join tb_user_name b on a.id = b.id
# a.id age b.id name
# 2 11 2 zhang
# 3 12 3 li
# 4 13 4 zhou
# 1 10 <null> <null>
# <null><null> 5 chen