• SQL用了Union后的排序问题


    原文:https://blog.csdn.net/sinat_35861727/article/details/65628037

    最近使用SQL语句进行UNION查询,惊奇的发现:SQL没问题,UNION查询也没问题,都可以得到想要的结果,可是在对结果进行排序的时候,却出问题了。

    1.UNION查询没问题

    1.  
      SELECT `id`,`username`,`mobile`,`time`,id AS leader
    2.  
      FROM `grouporder_leader`
    3.  
      WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
    4.  
      UNION ALL
    5.  
      SELECT leadorderid,username,mobile,time,null
    6.  
      FROM `grouporder_partner`
    7.  
      WHERE courseid=21 and status=1 and merchid=23

    结果如下

    2.排序就出问题了

    1.  
      SELECT `id`,`username`,`mobile`,`time`,id AS leader
    2.  
      FROM `grouporder_leader`
    3.  
      WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
    4.  
      ORDER BY time DESC
    5.  
      UNION ALL
    6.  
      SELECT leadorderid,username,mobile,time,null
    7.  
      FROM `grouporder_partner`
    8.  
      WHERE courseid=21 and status=1 and merchid=23
    9.  
      ORDER BY time DESC

    执行这条SQL语句之后就报错。

    3.创建临时表

    使用类似于创建临时表的方法保存查询结果,然后对临时表进行查询排序。

    1.  
      SELECT id,username,mobile,time,leader
    2.  
      FROM (SELECT `id`,`username`,`mobile`,`time`,id AS leader
    3.  
      FROM `grouporder_leader` WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
    4.  
      UNION ALL
    5.  
      SELECT leadorderid,username,mobile,time,null
    6.  
      FROM `grouporder_partner` WHERE courseid=21 and status=1 and merchid=23
    7.  
      )
    8.  
      ORDER BY time DESC

    4.起别名

    不知道为什么第3步中查询依旧没有,然后对UNION查询的结果起个别名,然后再查询排序就没问题了。

    1.  
      SELECT a.id,a.username,a.mobile,a.time,a.leader
    2.  
      FROM (SELECT `id`,`username`,`mobile`,`time`,id AS leader
    3.  
      FROM `grouporder_leader` WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
    4.  
      UNION ALL
    5.  
      SELECT leadorderid,username,mobile,time,null
    6.  
      FROM `grouporder_partner` WHERE courseid=21 and status=1 and merchid=23
    7.  
      ) AS a
    8.  
      ORDER BY time DESC

    结果就正确了

    查出来就好说了,再进行去重或者其他操作,也没问题.

      1.  
        SELECT DISTINCT a.id,a.username,a.mobile,FROM_UNIXTIME(a.time,'%Y/%m/%d') as _time,a.leader
      2.  
        FROM (SELECT `id`,`username`,`mobile`,`time`,id AS leader
      3.  
        FROM `grouporder_leader` WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
      4.  
        UNION ALL
      5.  
        SELECT leadorderid,username,mobile,time,null
      6.  
        FROM `grouporder_partner` WHERE courseid=21 and status=1 and merchid=23
      7.  
        ) AS a
      8.  
        ORDER BY time DESC
      9.  

  • 相关阅读:
    解析Javascript事件冒泡机制(转)
    JavaScript事件处理的三种方式(转)
    javaScript中"=="和"==="运算符的区别
    博客
    基础知识巩固二
    基础知识巩固
    知识小结(浮点数问题)
    关于电脑桌面图标消失并且右键无法点击的情况
    JS随笔(二)
    关于JS学习笔记
  • 原文地址:https://www.cnblogs.com/tc310/p/9248217.html
Copyright © 2020-2023  润新知