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语句相同,都会对结果进行去重。
至于在实际使用场景中哪个会更简单,哪个运算速度更快,需要不断尝试,并无定论。