SQL用了Union后的排序问题

2022-07-07 09:28:02 浏览数 (1)

最近使用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

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/113608.html原文链接:https://javaforall.cn

0 人点赞