MySql按条件不同的顺序

时间:2014-03-10 10:16:42

标签: php mysql sql-order-by

我有我的mysql查询

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

给我回报

mysql query result

问题是,如果部分有级别> 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的部分结果进行排序。

4 个答案:

答案 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