简体   繁体   中英

MySql different order by conditions

I have my mysql query

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

returns me

mysql查询结果

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.

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.

First of all, the WHERE 1 part is useless. You don't need WHERE to specify an ORDER clause.

Then, use 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

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

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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