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组合两多个表时,不考虑结果集中是否存在重复记录。

猜你喜欢

转载自blog.csdn.net/HelloKitty520123/article/details/89394593
今日推荐