簡體   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