Sql合并两个select查询,union,union all

 

现有2个查询,需要将每个查询的结果合并起来(注意不是合并结果集,因此不能使用union),可以将每个查询的结果作为临时表,然后再从临时表中select所需的列,示例如下:

创建测试表user_info数据如下:

如上表所示,user_info记录了每个用户每次考试的成绩。如果合格线为60分,需要统计出每个用户参与考试的总次数及及格的次数。

select totaldata.user_name,totaldata.totalnum as totalnum ,okdata.oknum as oknum from 
(
select a.user_name ,count(a.user_name)as totalnum from user_info a  GROUP BY user_name
) as totaldata,
(
select a.user_name ,count(a.user_name)as oknum from user_info a where a.user_score > 60 GROUP BY user_name
)as okdata
where totaldata.user_name = okdata.user_name

 

如上,由于用户“红叶”两次参与考试,一次“20”,一次“30”,所以没有及格过,第二个子查询okdata就没有红叶的记录,导致最终关联的结果看不到“红叶”。考虑通过left join查询:

select totaldata.user_name,totaldata.totalnum as totalnum ,okdata.oknum as oknum from 
(
select a.user_name ,count(a.user_name)as totalnum from user_info a  GROUP BY user_name
) as totaldata 
 LEFT JOIN
(
select a.user_name ,count(a.user_name)as oknum from user_info a where a.user_score > 60 GROUP BY user_name
)as okdata
on totaldata.user_name = okdata.user_name

left join结果如下:

 

 

union all操作结果如下:

select a.user_name ,count(a.user_name)as totalnum from user_info a  GROUP BY user_name
UNION ALL
select a.user_name ,count(a.user_name)as oknum from user_info a where a.user_score > 60 GROUP BY user_name

 

union操作结果如下:

select a.user_name ,count(a.user_name)as totalnum from user_info a  GROUP BY user_name
UNION 
select a.user_name ,count(a.user_name)as oknum from user_info a where a.user_score > 60 GROUP BY user_name

union 与 union all语句的区别
 UNION 组合多个表(或结果集)并将其作为单个结果集返回;
UNION ALL 在结果中包含所有的行,包括重复行。
也就是说,使用UNION组合两个表时,将重复的记录删除;

而使用UNION ALL组合两多个表时,不考虑结果集中是否存在重复记录。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值