数据库Join查询:内联、左外联、右外联、取交集
2019-07-03 本文已影响0人
程序员网址导航
原文:RelaxHeart网 - Tec博客: 库Join查询:内联、左外联、右外联、取交集
前言
示例:
在MySQL创建两张表:a_table、b_table
CREATE TABLE `a_table` (
`a_id` int(11) DEFAULT NULL,
`a_name` varchar(10) DEFAULT NULL,
`a_part` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `b_table` (
`b_id` int(11) DEFAULT NULL,
`b_name` varchar(10) DEFAULT NULL,
`b_part` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
随便插入几条数据:
INSERT INTO `a_table` (`a_id`, `a_name`, `a_part`)
VALUES
(1, '王琦', '复杂网络部'),
(2, 'tom', '信贷风控部'),
(3, 'nice', '信贷风控部');
INSERT INTO `b_table` (`b_id`, `b_name`, `b_part`)
VALUES
(1, '王琦', '复杂网络部'),
(2, 'tom', '信贷风控部'),
(4, 'fee', '汽车金融部');
a表查询结.png
b表查询结果.png
内联(inner Join on)
# 内联查询:inner join on
select * from a_table a inner join b_table b on a.a_id = b.b_id;
组合两个表中的记录,返回关联字段相符的记录,也就是两个表的交集
内联查询结果.png
左外联(left join On / left outer join )
# 左连接 / 左外连接 : left join on
select * from a_table a left join c_table b on a.a_id = b.a_id;
left join 是left outer join的简写,它的全称是左外连接,是外连接中的一种。
左表全部记录都会显示出来,右表只显示出满足条件的记录,不足的列全部显示NULL
左外联查询结果.png右外联(right join On / right outer join on)
# 右连接 / 右外连接 : right join on
select * from a_table a right join b_table b on a.a_id = b.b_id;
right join 是 right outer join的简写,它的全程是右外连接,是外链接的一种。
右表全部记录都会显示出来,左表只显示满足条件的记录,不足的列全部显示NULL
右外联查询结果.png取并集(full join on)
有了内联、外联查询,有没有取并集查询呢?当然也有了:
select * from a_table a full join b_table b on a.a_id = b.b_id
注意:查询报错了!!!
这是因为MySQL中不支持full join,那在mysql中如何实现两个表取并集呢?
我们可以用
union
查询
取并集(union)
左外查询 union 右外查询
select * from a_table a left join b_table b on a.a_id = b.b_id
union
select * from a_table a right join b_table b on a.a_id = b.b_id
UNION.png
UNION定义:UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
注意:
UNION
和UNION ALL
区别:UNION ALL会列出所有结果,有重复,UNION没有重复
select * from a_table a left join b_table b on a.a_id = b.b_id
union all
select * from a_table a right join b_table b on a.a_id = b.b_id
UNION ALL.png
总结
inner join: 如果查询的表中都有至少一个匹配,则返回行
left join: 即使右表中没有匹配,也从左表返回所有的行
right join: 即使左表中没有匹配,也从右表返回所有的行
full join: 只要其中一个表中存在匹配,就返回行,但是在mysql中不支持
union:合并多个查询语句的结果集(去重)
union all:合并多个查询语句的结果集(不去重)
更多文章:RelaxHeart网更多博文