繁体   English   中英

MySQL条件不同的顺序

[英]MySql different order by conditions

我有我的MySQL查询

SELECT `adddate`, `pexpdate`, `level` FROM `localhost-tests` WHERE 1 ORDER BY `level` DESC, `pexpdate` DESC, `adddate` DESC

还给我

mysql查询结果

问题是,如果级别> 0的部分很好,并按pexpdate排序,则级别= 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的部分结果进行排序。

首先, 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

您可以使用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`

尝试不带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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM