原文:https://blog.csdn.net/sinat_35861727/article/details/65628037
最近使用SQL语句进行UNION查询,惊奇的发现:SQL没问题,UNION查询也没问题,都可以得到想要的结果,可是在对结果进行排序的时候,却出问题了。
1.UNION查询没问题
-
SELECT `id`,`username`,`mobile`,`time`,id AS leader
-
FROM `grouporder_leader`
-
WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
-
UNION ALL
-
SELECT leadorderid,username,mobile,time,null
-
FROM `grouporder_partner`
-
WHERE courseid=21 and status=1 and merchid=23
结果如下
2.排序就出问题了
-
SELECT `id`,`username`,`mobile`,`time`,id AS leader
-
FROM `grouporder_leader`
-
WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
-
ORDER BY time DESC
-
UNION ALL
-
SELECT leadorderid,username,mobile,time,null
-
FROM `grouporder_partner`
-
WHERE courseid=21 and status=1 and merchid=23
-
ORDER BY time DESC
执行这条SQL语句之后就报错。
3.创建临时表
使用类似于创建临时表的方法保存查询结果,然后对临时表进行查询排序。
-
SELECT id,username,mobile,time,leader
-
FROM (SELECT `id`,`username`,`mobile`,`time`,id AS leader
-
FROM `grouporder_leader` WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
-
UNION ALL
-
SELECT leadorderid,username,mobile,time,null
-
FROM `grouporder_partner` WHERE courseid=21 and status=1 and merchid=23
-
)
-
ORDER BY time DESC
4.起别名
不知道为什么第3步中查询依旧没有,然后对UNION查询的结果起个别名,然后再查询排序就没问题了。
-
SELECT a.id,a.username,a.mobile,a.time,a.leader
-
FROM (SELECT `id`,`username`,`mobile`,`time`,id AS leader
-
FROM `grouporder_leader` WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
-
UNION ALL
-
SELECT leadorderid,username,mobile,time,null
-
FROM `grouporder_partner` WHERE courseid=21 and status=1 and merchid=23
-
) AS a
-
ORDER BY time DESC
结果就正确了
查出来就好说了,再进行去重或者其他操作,也没问题.
-
SELECT DISTINCT a.id,a.username,a.mobile,FROM_UNIXTIME(a.time,'%Y/%m/%d') as _time,a.leader
-
FROM (SELECT `id`,`username`,`mobile`,`time`,id AS leader
-
FROM `grouporder_leader` WHERE `courseid` = 21 AND `merchid` = 23 AND `status` = 1
-
UNION ALL
-
SELECT leadorderid,username,mobile,time,null
-
FROM `grouporder_partner` WHERE courseid=21 and status=1 and merchid=23
-
) AS a
-
ORDER BY time DESC
-