简体   繁体   中英

Mysql order by two columns if one is grater than timestamp

I have this SQL SELECT in PHP:

SELECT * 
  FROM ads 
 ORDER BY ad_sponsored_date DESC, ad_date DESC

I want to display a list of ads, they are normally sorted by date but if one is sponsored, then it appears in top. The above does that nicely; but I need to also test if that ad_sponsored_date is not grater than timestamp and if so, then only sort by the second one (ad_date) , is it possible?

Something like this but I don't know the correct syntax:

SELECT * 
  FROM ads 
 ORDER BY (ad_sponsored_date DESC IF ad_sponsored_date > $timestamp, ad_date DESC)

This captures your logic in SQL:

SELECT *
FROM ads
ORDER BY (case when ad_sponsored_date > $timestamp then ad_sponsored_date end) desc,
         ad_date DESC;

I am, however, unclear on what to do for the "else" part of the if.

Note: in MySQL NULL values are placed last for a descending sort, which is why this puts the sponsored ads at the top of the list.

Try

SELECT * 
  FROM ads 
  ORDER BY CASE WHEN ad_sponsored_date > '$timestamp'
                THEN ad_sponsored_date 
                ELSE ad_date END DESC

Here is SQLFiddle demo

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