gpt4 book ai didi

MySQL 按日期和优先级排序

转载 作者:行者123 更新时间:2023-11-29 04:50:19 25 4
gpt4 key购买 nike

我有一个网页,其中有一张表中的新闻数据。

在许多情况下,我使用以下 SQL:

SELECT * FROM table ORDER BY insertDate DESC

订购。

ID|priority|insertDate
1 |NULL |2012-09-16
2 |NULL |2012-09-17
3 |NULL |2012-09-18
5 |NULL |2012-09-19
5 |NULL |2012-09-20
4 |1 |2010-05-10 - this is way back in the future

但是用户想要优先处理 1 个新闻。如果我使用

 SELECT * FROM table ORDER BY priority ASC ,insertDate DESC

它不能正常工作,我必须如何使用 ORDER 才能得到结果

ID|priority|insertDate
4 |1 |2010-05-10
1 |NULL |2012-09-16
2 |NULL |2012-09-17
3 |NULL |2012-09-18
5 |NULL |2012-09-19
5 |NULL |2012-09-20

最佳答案

Use coalesce将有效值设置为 Null 优先级行:

SELECT * 
FROM table
ORDER BY
coalesce(priority,0) ASC ,
insertDate DESC

已编辑

重新阅读您的问题,我发现正确的顺序是 DESC 而不是 ASC:

   coalesce(priority,0) DESC ,

另外,请注意@yshavit 评论。为了提高性能,您可以将查询拆分为两个选择,第一个不包含空值。

请记住,当您创建这个新字段时,您 can set to it a default value ,这将避免 coalesceunion:

data_type [NOT NULL | NULL] [DEFAULT default_value]

关于MySQL 按日期和优先级排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12507549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com