我有我的mysql查询
SELECT `adddate`, `pexpdate`, `level` FROM `localhost-tests` WHERE 1 ORDER BY `level` DESC, `pexpdate` DESC, `adddate` DESC
给我回报
问题是,如果部分有级别> 0很好,按pexpdate排序,第二部分,其中level = 0,必须按adddate排序,而不是pexpdate。
我试过了:
WHERE 1 ORDER BY ORDER BY `level` desc, `PExpDate` desc, `AddDate` desc
WHERE 1 ORDER BY IF(`level`, `PExpDate`, `AddDate`) DESC
WHERE 1 ORDER BY level DESC, ifnull(PExpDate, AddDate) DESC LIMIT 5
问题:如何通过adddate对level = 0的部分结果进行排序。
答案 0 :(得分:1)
首先,WHERE 1
部分是无用的。您不需要WHERE
来指定ORDER
子句。
然后,使用UNION
。
SELECT `adddate`, `pexpdate`, `level` FROM `localhost-tests` WHERE `level` <> 0 ORDER BY `level` DESC, `pexpdate` DESC, `adddate` DESC
UNION
SELECT `adddate`, `pexpdate`, `level` FROM `localhost-tests` WHERE `level` = 0 ORDER BY `adddate` DESC
答案 1 :(得分:1)
您可以使用UNION
SELECT `adddate`, `pexpdate`, `level` FROM `localhost-tests` WHERE `level`>0 ORDER BY `level` DESC, `pexpdate` DESC
UNION
SELECT `adddate`, `pexpdate`, `level` FROM `localhost-tests` WHERE `level`=0 ORDER BY `adddate`
答案 2 :(得分:1)
尝试没有UNION
SELECT `adddate`, `pexpdate`, `level` FROM `localhost-tests`
ORDER BY CASE WHEN `level`>0 THEN `level` , `pexpdate` , `adddate`
WHEN `level`=0 THEN `adddate`
END DESC
答案 3 :(得分:0)
解决方案很简单,乘以2列并按结果排序
SELECT *, `level` * UNIX_TIMESTAMP(`pexpdate`) as `BonusDate` FROM `localhost-tests` WHERE 1 ORDER BY `BonusDate` DESC, `adddate` DESC