MySQL(17):Select-union(联合查询)使用注意事项

1. 需求:

获得0115班所有的代课教师代课天数,结果按照升序排序;同时获得0228班,结果按照降序排序
(1)首先查询原来的0115班和0228班所有代课天数,如下:
 
 
 
(2)使用union关键字,如下:
 
 
(3)修改韩信在php0115班的记录都是days =15,如下:
 
 
 
(4)此时我们再去使用union组合查询,就会出现问题,如下:

 

注意:

        如果union的结果存在重复的记录,那么就会消除重复,类似执行了distinct操作。
该怎么解决这个问题?
        可以通过union选项all来达到目的.
   (select t_name,days from teacher_class where c_name='php0115' order by days limit 10)union allselect t_name,days from teacher_class where c_name='php0228' order by days desc limit 10
);
 
 
 
2. 注意:
修改上面的SQL语句为:
  (select t_name,days from teacher_class where c_name='php0115' order by days )union allselect t_name,days from teacher_class where c_name='php0228' order by days desc 
);

去掉了上面limit 10,查询的结果没有按照预想的排序显示
 
 
 
排序:
子语句结果的排序:
(1). 将子语句包裹在子括号内。
(2). 子语句的order by只有在order by 配合limit时候,才生效的。原因是:
union在做子语句时候,会对limit子句的order by优化(忽略)
 
原文地址:https://www.cnblogs.com/hebao0514/p/4885775.html