简体   繁体   中英

How can I sort by a different column if first choice is null

I have a movie database. I want to sort by released date but when released date is missing (null or empty) i want to sort by dateAdded instead

SELECT 
    movie.ID,
    Title,
    released,
    dateAdded
FROM
    movie
WHERE
    dateAdded is not null 
    and (released <= CURDATE() or released is null or released ='')
ORDER BY released DESC
LIMIT 50

Usually you do it like this:

ORDER BY IFNULL(released, dateAdded)

That's somewhat abusive since it can't be indexed properly but will work on relatively large amounts of data without bogging down too badly.

最好使用Standard SQL的COALESCE而不是专有的ISNULL

ORDER BY COALESCE(released, dateAdded) 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