数据库查询,对输出结果要求输出顺序和去重(union 、union all)

说起顺序,想起来的就是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 = '男';

这样输出结果就先输出学校再输出性别,并且允许有重复列的出现。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值