[英]MySql different order by conditions
I have my mysql query 我有我的MySQL查询
SELECT `adddate`, `pexpdate`, `level` FROM `localhost-tests` WHERE 1 ORDER BY `level` DESC, `pexpdate` DESC, `adddate` DESC
returns me 还给我
Problem is, if part with levels > 0 is fine, and sorted by pexpdate, second part, where level = 0, must be sorted by adddate, not pexpdate. 问题是,如果级别> 0的部分很好,并按pexpdate排序,则级别= 0的第二部分必须按adddate而不是pexpdate排序。
I've tried: 我试过了:
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
Question: How to sort part of result where level = 0 by adddate. 问题:如何通过adddate对level = 0的部分结果进行排序。
First of all, the WHERE 1
part is useless. 首先, WHERE 1
部分没有用。 You don't need WHERE
to specify an ORDER
clause. 您不需要WHERE
来指定ORDER
子句。
Then, use UNION
. 然后,使用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
You can use a UNION
您可以使用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`
try that without UNION 尝试不带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
解决方案很简单,将2列相乘并按结果排序
SELECT *, `level` * UNIX_TIMESTAMP(`pexpdate`) as `BonusDate` FROM `localhost-tests` WHERE 1 ORDER BY `BonusDate` DESC, `adddate` DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.