说起顺序,想起来的就是order by ;说起去重,想起来的就是distinct。然鹅,刷到下面这道题,要求对输出结果而不是输出数值做上述操作,就不能再使用以前那种方法了。
今天要使用的是union关键字,和union all关键字,以下面题型为案例:
输出的结果是:
注意两个要素:
- 先输出对应学校;
- 再输出对应性别
以下是几种猜想:
1、使用where语句
select device_id, gender, age, gpa
from user_profile where university = '山东大学' or gender = '男';
where语句虽然可以加限制条件,但是这个输出结果,虽然有or关键字,但不满足先输出学校再输出性别。
2、union
union对多个查询的结果集进行并集处理,并且进行去重操作;
union还会对结果集进行默认排序操作。
用union处理这个问题:
select device_id, gender, age, gpa
from user_profile where university = '山东大学'
union
select device_id, gender, age, gpa
from user_profile where gender = '男';
但是,没有达到题目要求的 “不去除重复列”,所以也不符合要求。
3、union all
与union不同的地方在于,
union all对结果集进行并集处理,但是不去重,包含重复行;
union all也不对结果集进行排序。
下面用union all处理:
select device_id, gender, age, gpa
from user_profile where university = '山东大学'
union all
select device_id, gender, age, gpa
from user_profile where gender = '男';
这样输出结果就先输出学校再输出性别,并且允许有重复列的出现。