上节课我们给大家介绍了常用的MySQL多表联合查询用法,知道了left join /right join /inner join 的基本用法。具体请回顾关于MySQL多表联合查询,你真的会用吗?本节课我们继续展开讲讲MySQL多表联合查询的其他用法——全连接与笛卡尔连接。
01
全连接union&union all
首先看什么是全连接,具体可以看以下韦恩图。
全连接定义:全连接全称为全外连接,它也是外连接的一种。它将左右两个表通过ON进行条件连接,并且最后列出左右两个表的所有记录。
但在MySQL中,它是不支持全连接这种用法的,不过可以使用union或union all进行弥补。例如,现在我们想把上节课左连接与右连接的结果合并起来,即我们想把使用华为手机的乘客编号、姓名、是否幸存、船舱等级和手机品牌与船舱等级为3且存活的乘客编号、姓名、是否幸存、船舱等级和手机品牌两种查询结果合并,我们看分别使用union和union all该怎么做。
【union】
SELECT a.PassengerId,a.name,b.survived,b.pclass,a.phonebrand
from phone a
left join titanic b
on a.PassengerId=b.passengerId
where a.phonebrand="HUAWEI"
UNION
SELECT a.passengerId,a.name,b.survived,b.pclass,a.phonebrand
from phone a
right join titanic b
on a.PassengerId=b.passengerId
where b.survived=1
and b.pclass=3;
使用union查询结果如下
【union all】
SELECT a.PassengerId,a.name,b.survived,b.pclass,a.phonebrand
from phone a
left join titanic b
on a.PassengerId=b.passengerId
where a.phonebrand="HUAWEI"
UNION all
SELECT a.passengerId,a.name,b.survived,b.pclass,a.phonebrand
from phone a
right join titanic b
on a.PassengerId=b.passengerId
where b.survived=1
and b.pclass=3;
使用union all 查询结果如下
可以看到,相同的查询语句union的查询结果为23行记录,而union all 的查询结果为131行记录。因此,可以简单总结union 与union all 两种查询结果的要点与区别如下:
02
笛卡尔连接cross join
MySQL笛卡尔连接是MySQL中的一种连接方式,区别于内连接和外连接,对于cross join连接来说,其实使用的就是笛卡尔连接。在MySQL中,当两个表使用了笛卡尔连接时,cross join会产生一个结果集,该结果集是两个关联表的行的乘积。通常,如果每个表分别具有n和m行,则结果集将具有n*m行。
例如,我们已知phone表有2097006行记录,titanic表有891行记录,那么两者做笛卡尔连接的总记录数就是2097006x891=1868432346,其基本用法如下。(由于结果太大,我们就不实际运行了)
SELECT * from phone a
cross join titanic b
03
总结
以上就是我们本节课要介绍的全部内容,总结一下: