I'm trying to get the correct ORDER BY
for my MySQL query, however I can't get the order by correct.
I have two columns:
breaking_news
= values are NULL
or 1
news_published_dt
= values are DATETIME
How can I sort so that the first output are breaking_news NOT NULL
sorted by DATETIME
, and then the rest afterwards is just ordered by DATETIME
?
I've tried this, but it gave me no output
ORDER BY CASE WHEN n.breaking_news IS NOT NULL THEN 1 ELSE 2 END, n.news_published_dt DESC
Looks like, you are looking for this:
SELECT
*
FROM
tableName
ORDER BY
breaking_news DESC,
news_published_dt ASC
SELECT * FROM table_name ORDER BY news_published_dt DESC
select * from
(select *, 1 Shortby from table 1 where (breaking_news is null)
union all
select *, 2 Shortby from table 1 where (breaking_news=1)
) a
order by Shortby ,news_published_dt Desc
SORT BY in MySQL works differently than what you (me included) would be expected. You cannot do a sort by of two columns and have each of the first sorted by columns sorted according to the second.
DOES NOT WORK:
ORDER BY breaking_news, news_published_dt
RESULT:
breaking_news | news_published_dt
1 | 2019-04-17
1 | 2019-04-04
null | 2019-05-01
null | 2019-05-06
The only way that I have found to accomplish this; query for the wanted boolean result individually and then union the two together.
THIS DOES WORK:
(SELECT * FROM news_table WHERE breaking_news = 1 ORDER BY news_published_dt)
UNION
(SELECT * FROM news_table WHERE breaking_news <> 1 ORDER BY news_published_dt)
RESULT:
breaking_news | news_published_dt
1 | 2019-04-04
1 | 2019-04-17
null | 2019-05-01
null | 2019-05-06
For a more thorough explanation of this, check out Edwin Wang's explanation
当 n.break_news 不为 NULL 时使用此顺序,然后 n.break_news ELSE 'zzzzzzzzzzzzzzzzzzzzzzzz' END, n.news_published_dt 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.