联系:union/union all 将两个或多个select结果合并在一起。
区别:union 合并后去重;union all 合并后不去重。
示例:应用场景简述,union用于合并后去重,如校长要查看语文、数学成绩60分以上的同学姓名,只需要提供筛选后的姓名即可,多个名字无意义,所以要去重;union all 合并不去重,如语文老师、数学老师都想奖励60分以上同学各一支钢笔,此时关注单科成绩60的人次来购买钢笔,所以不能去重。
准备工作:
--表1语文成绩单
create table yuwen(
name string ,
score int
);
--表2数学成绩单
create table shuxue(
name string ,
score int
);
INSERT into yuwen
VALUES ('zs',90),('ls',80);
INSERT into shuxue
VALUES ('zs',99),('ls',100);
测试:
--union
SELECT name
from yuwen
where score > 60
union
SELECT name
from yuwen
where score > 60
;
对应结果
--name
--ls
--zs
--union all
SELECT name
from yuwen
where score > 60
union all
SELECT name
from yuwen
where score > 60
;
对应结果
--name
--zs
--ls
--zs
--ls
本文介绍了SQL中的union和unionall关键字在合并两个或多个select查询结果时的不同,union用于去除重复项,适用于查看特定条件下的唯一结果;而unionall则不进行去重,适合统计满足条件的总次数。通过创建语文和数学成绩表的示例,展示了这两个操作在实际场景中的使用。
3690

被折叠的 条评论
为什么被折叠?



