# join 关键字左右各有一个表# inner join - 查找满足 condition 的条目(即 A B 交集)并显示, join 默认处理方式是这个# left join - 取 A 全部显示, B 没有对应值显示为 null# right join - 取 B 全部显示, A 没有对应值显示为 null# full join - 取并集, 没有对应值显示为 nullselect<select_list>from T1 [inner|left|right|full]join T2 on condition [where condition isnull]
图示
示例表结构和数据内容
# 这是示例的表结构和数据内容createtable stu(
name varchar(20),
age intdefault18,
num intunique);createtable score(
num intunique,
math int,
chinese int);insertinto stu(name, num)values("Tom",1001),("Tim",1002),("Aki",1003);insertinto score values(1001,100,99),(1002,100,100),(1004,99,99),(1005,98,100);
查询示例
inner join
select stu.name, s.math, s.chinese from stu innerjoin score as s on stu.num = s.num;# 结果# name math chinese# Tom 100 99# Tim 100 100
left join
select stu.name, s.math, s.chinese from stu leftjoin score as s on stu.num = s.num;# 结果# name math chinese# Tom 100 99# Tim 100 100# Aki (null) (null) # 取 A 表全部, B 表没有对应值显示为 null# ----------# 后边加上 where T2.column is null, 只显示没有对应值的部分select stu.name, s.math, s.chinese from stu leftjoin score as s on stu.num = s.num\
where s.num isnull;# 结果# Aki (null) (null)
right join
select stu.name, s.math, s.chinese from stu rightjoin score as s on stu.num = s.num;# 结果# name math chinese# Tom 100 99# Tim 100 100# (null) 99 99 # 取 B 表全部, A 表没有对应值显示为 null# (null) 98 100# ----------# 后边加上 where T1.column is null, 只显示没有对应值的部分select stu.name, s.math, s.chinese from stu leftjoin score as s on stu.num = s.num\
where stu.num isnull;# 结果# (null) 99 99# (null) 98 100
full outer join (存疑, 有时候会报错)
# left join 和 right join 结果的并集select stu.name, s.math, s.chinese from stu fullouterjoin score as s on stu.num = s.num;# 结果# name math chinese# Tom 100 99# Tim 100 100# Aki (null) (null)# (null) 99 99# (null) 98 100# ----------# 后边加上 where T1.column is null or T2.column is null, 只显示没有对应值的部分select stu.name, s.math, s.chinese from stu fullouterjoin score as s on stu.num = s.num\
where s.num isnullor stu.num isnull;# 结果# Aki (null) (null)# (null) 99 99# (null) 98 100