MySQL 学习笔记(四)多表查询

48 阅读2分钟

1.概述

多表连接有哪些分类和连接方法:

  1. 内连接 join,inner join
  2. 外连接 left join, left outer join, right join,right outer join, union
  3. 交叉连接 cross join

2. 实例分析

TableA: image.png

TableB: image.png

2.1 内连接

应用场景:

image.png

这种场景下得到的是满足某一条件的A,B内部的数据;正因为得到的是内部共有数据,所以连接方式称为内连接。

语法:

select  *  from  tablea, tableb where ...
 
等价于
 
select  *  from  tablea  inner  join  tableb
 
推荐使用inner join这种写法
 
)

实例:

select a.*, b.* from tablea a
inner join tableb b
on a.id = b.id

或

select a.*, b.* from tablea a
join tableb b
on a.id = b.id

结果如下:

image.png

2.2 外连接(六种场景)

image.png

2.2.1 left join 或者left outer join(等同于left join)

应用场景:

image.png

select a.*, b.* from tablea a
left join tableb b
on a.id = b.id

或

select a.*, b.* from tablea a
left outer join tableb b
on a.id = b.id

结果如下,TableB中不存在的记录填充Null:

image.png

2.2.2 left join 或者left outer join(等同于left join) +  [ where B.column is null ]

应用场景:

image.png

select a.id aid,a.age,b.id bid,b.name from tablea a
left join tableb b
on a.id = b.id
Where b.id is null

left join表a的数据全部显示,匹配表b的数据也显示,而b.id再次过滤掉 表b的id为空的。

结果如下:

image.png

2.2.3  right join 或者right outer join(等同于right join)

应用场景:

image.png

select a.id aid,a.age,b.id bid,b.name from tablea a
right join tableb b
on a.id = b.id

image.png

结果如下:

image.png

2.2.4 right join 或者right outer join(等同于right join) +  where A.column is null

应用场景:

image.png

image.png

结果如下:

image.png

2.3 交叉连接 (cross join)

2.3.1 实际应用中还有这样一种情形,想得到A,B记录的排列组合,即笛卡儿积,这个就不好用集合和元素来表示了。需要用到cross join:

select a.id aid,a.age,b.id bid,b.name from tablea a
cross join tableb b

image.png

2.3.2 还可以为cross  join指定条件 (where):

select a.id aid,a.age,b.id bid,b.name from tablea a
cross join tableb b
where a.id = b.id

image.png 结果如下:

image.png 注:这种情况下实际上实现了内连接的效果