我们经常说union和union all的区别在于:
1.union 合并相同的列时,会去重只取其中的一条;
2.union all 合并所有的列。
但是如果在按照某一条件进行查询时,如果表中数据没有符合该条件的记录。(即按此条件查询,表中查找到的的记录每列都为空)此时union all并不能合并这种空的记录。
比如新建一个表名为t_student的表。记录学生的姓名,性别,年龄和成绩等基础信息。
在t_student表中查询名为李明,小河,张三的姓名和成绩。
select username,grade from t_student where username ='李明'
union all
select username,grade from t_student where username ='小河'
union all
select username,grade from t_student where username ='张三'
查询结果如下:
我们可以发现如果在t_student表中并没有张三的信息,那么使用union all,为空的记录并不会在出现查询结果中。但是如果在t_student表添加名为张三的一列(除学生姓名外,他们列都为空)都会在查询结果中显示张三的记录。