ORDER BY在查询中不起作用

时间:2018-02-27 09:50:48

标签: mysql sql-order-by

我有一个查询来获取分组依据和排序依据。我在分组中获得结果,但不是按顺序。你能帮忙吗?

这是我的查询

from moviepy.editor import *

screensize = (720,460)
txtClip = TextClip('enlarge', color='white', font="Amiri-Bold",
                    kerning=5, fontsize=50)
text_annimation = txtClip.set_duration(2).resize(lambda t : (1 + 2*t/2)).set_pos('center')

final_clip = CompositeVideoClip([text_annimation],size=screensize).set_fps(24)

我没有按顺序得到这个结果。

(
SELECT v.STATUS, COUNT(v.STATUS) AS COUNT
FROM mdl_ctx_voucher v
WHERE 
MONTH(FROM_UNIXTIME(v.timecreated)) = MONTH(CURDATE()) AND
MONTH(FROM_UNIXTIME(v.timemodified)) = MONTH(CURDATE()) AND 
YEAR(FROM_UNIXTIME(v.timecreated)) = YEAR(CURDATE()) AND 
YEAR(FROM_UNIXTIME(v.timemodified)) = YEAR(CURDATE())
GROUP BY v.STATUS ORDER BY v.`status` DESC
)
UNION
(
SELECT DISTINCT(STATUS),0 as count
FROM mdl_ctx_voucher
WHERE STATUS NOT IN (
SELECT mainQuery.status
FROM 
(
SELECT COUNT(v.STATUS) AS COUNT, v.STATUS
FROM mdl_ctx_voucher v
WHERE 
MONTH(FROM_UNIXTIME(v.timecreated)) = MONTH(CURDATE()) 
AND MONTH(FROM_UNIXTIME(v.timemodified)) = MONTH(CURDATE()) 
AND YEAR(FROM_UNIXTIME(v.timecreated)) = YEAR(CURDATE()) 
AND YEAR(FROM_UNIXTIME(v.timemodified)) = YEAR(CURDATE())
GROUP BY v.STATUS ORDER BY v.`status` DESC
)mainQuery) ORDER BY v.`status` DESC
)

我希望按状态排序顺序生成此结果。

1 个答案:

答案 0 :(得分:2)

最后添加order by。比它影响整个结果。在您的代码中,它只会影响union

的第二部分
select Status, Count from (
SELECT v.STATUS, COUNT(v.STATUS) AS COUNT
FROM mdl_ctx_voucher v
WHERE 
MONTH(FROM_UNIXTIME(v.timecreated)) = MONTH(CURDATE()) AND
MONTH(FROM_UNIXTIME(v.timemodified)) = MONTH(CURDATE()) AND 
YEAR(FROM_UNIXTIME(v.timecreated)) = YEAR(CURDATE()) AND 
YEAR(FROM_UNIXTIME(v.timemodified)) = YEAR(CURDATE())
GROUP BY v.STATUS 
)
UNION
(
SELECT DISTINCT(STATUS),0 as count
FROM mdl_ctx_voucher
WHERE STATUS NOT IN (
SELECT mainQuery.status
FROM 
(
SELECT COUNT(v.STATUS) AS COUNT, v.STATUS
FROM mdl_ctx_voucher v
WHERE 
MONTH(FROM_UNIXTIME(v.timecreated)) = MONTH(CURDATE()) 
AND MONTH(FROM_UNIXTIME(v.timemodified)) = MONTH(CURDATE()) 
AND YEAR(FROM_UNIXTIME(v.timecreated)) = YEAR(CURDATE()) 
AND YEAR(FROM_UNIXTIME(v.timemodified)) = YEAR(CURDATE())
GROUP BY v.STATUS 
)mainQuery) 
)ORDER BY status DESC