union关键字的用法很简单就是给每条select查询语句之间加上union关键字,那么他们的查询结果集就会都查询处理,union关键字也就意味着相当于“且”的意思。
测试数据:使用之前的MySQL的聚集函数的那一个测试表 MySQL的聚集函数
查看下面两个select查询:
select * from gather where price <5;
select * from gather where price >3;
因为都是同一张表,这里用*来代替,如果不同的表来测试union时,需要查询相同的字段
select *
from gather
where price < 5
union
select *
from gather
where price > 3;
我们会发现使用union时查询的数据少于两个分别查询之和,那些重复的查询结果只返回一个。如果想要重复的查询结果也要显示,那么就需要使用 union all
select *
from gather
where price < 5
union all
select *
from gather
where price > 3;
对于使用union组合查询的结果集要排序时,是能使用一个order by语句。而且它必须要放在最后一个select语句后面。
select *
from gather
where price < 5
union
select *
from gather
where price > 3
order by price;