MySQL 自学笔记_Union(组合查询)

1. Union查询简介

组合查询:有时在使用select语句进行数据查询时,想要将多个select语句在一个查询结果中输出,此时就需要使用Union关键字。

Union的使用方法:用union将多个select语句连接起来即可。例如:

所有男学生:

select stu_id, stu_grade, stu_sex 
from students 
where stu_sex = "male"; 

所有1年级学生:

select stu_id, stu_grade, stu_sex
from students
where stu_grade = 1;

将两个查询组合起来,只需用Union将两个查询语句简单组合即可。

select stu_id, stu_grade, stu_sex
from students
where stu_sex = "male"
union
select stu_id, stu_grade, stu_sex
from students
where grade = 1;

2. Union的使用规则

1). union中的每个查询语句必须包含相同的列、表达式或聚合函数。但是其出现顺序可以不同。

2). union的个select语句中的列的数据类型必须兼容:可以不必完全相同,但是要可以兼容。例如不同的日期类型。

3). union必须要有两个或两个以上的select语句。

3. Union 和 Union all

union默认会去除重复的行。即,在上面的例子中,同时满足两个条件的学生只会被返回一次。而不是在两个select字句各返回一次。

如果想要不去重,则需使用union all关键字。union all 的语句会返回1年级或者性别为男的学生。且同时满足两个条件的学生会被返回两次,即在每个select语句都会被查询并返回一次。

4. Union的结果的排序

组合查询结果的排序,order by字句要放在最后一个select 字句后面。不能对组合查询的各个select 字句单独排序,只能对所有union结果进行一次排序。例如:

select stu_name, stu_grade, stu_sex
from students
where stu_sex = "male"
union
select stu_name, stu_grade, stu_sex
from students
where stu_grade = 1
order by stu_name desc;

5. union并不是唯一方法

Union语句的效果也可以使用一个select 语句中的多个where 字句实现,如上面的例子:

select stu_name, stu_grade, stu_sex
from students
where 
stu_grade = 1
or
stu_sex = "male";

上面语句的效果和union语句相同,都会对结果进行去重。

至于在实际使用场景中哪个会更简单,哪个运算速度更快,需要不断尝试,并无定论。

转载于:https://www.cnblogs.com/myda/p/9541999.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值