当前位置: 代码网 > it编程>数据库>MsSqlserver > 数据库使用之union、union all、各种join的用法区别解析

数据库使用之union、union all、各种join的用法区别解析

2025年02月13日 MsSqlserver 我要评论
一、union 和union all1、区别:union去重,而union all不去重。2、注意点:1.被合并的每个select语句的列数、数据类型要相同(一一对应)。2.使用union时,由于可去

一、union 和union all

1、区别:

union去重,而union all不去重。

2、注意点:

1.被合并的每个select语句的列数、数据类型要相同(一一对应)。

2.使用union时,由于可去重性,可能导致数据丢失。

3.使用union all时,由于不可去重性,可能含重复的记录。

3、具体举例

【union】

【union all】

二、join关键字的区别

 1.left join和inner join区别

【长话短说】inner join(内连接)得到数据更少,直接剔除匹配不到的数据(剔除无关联id的数据),inner join = join。

【例子】如下图所示,inner join不显示红框的数据,left join会显示

select * from student s
left join score sc on s.id=sc.studentid

select * from student s
inner join score sc on s.id=sc.studentid

【查询匹配失败的数据】

select * from student s
left join score sc on s.id=sc.studentid
where sc.id is null --查询从表id为空的数据,就是联表匹配不到的数据

2.联表条件写法差异

--联表:只要满足关联关系,b.isdeleted是什么则返回什么
select * from tablea a
left join tableb b on a.id=b.exid 

--联表不筛选:只要满足关联关系,b.isdeleted≠0 则返回null
select * from tablea a
left join tableb b on a.id=b.exid and b.isdeleted=0

--联表且筛选:只要满足关联关系,b.isdeleted≠0 则返回null,假如是null则被where过滤掉
select * from tablea a
left join tableb b on a.id=b.exid
where b.isdeleted=0

--【结论】数据返回多少关系是:第一种=第二种>第三种
-- 因为第二种是a左联筛选后的b表,左外保证a表完整性,和第一种一样
-- 第三种是连接后再筛选,剔除的数据可能包含a表的数据

三、cross join

计算所有表的笛卡尔积:

总结 

到此这篇关于数据库使用之union、union all、各种join的用法区别解析的文章就介绍到这了,更多相关union、union all、join用法区别内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com