我有包含列的新闻表: id, title, brief, body, startDate, endDate, priority
我需要选择 3 个优先级最高的新闻,如果有超过 3 个关系,则根据最新的开始日期选择它们 我试过:
select * from (
select * from news order by priority DESC) as T
order by startDate DESC limit 3;
但问题是我的 SQL 语句将首先按优先级排序新闻,然后根据开始日期选择其中的 3 个,但这是不正确的,因为它可能需要优先级低于 max 的 3 个最新的 startDate 新闻....
我可以将限制 3 添加到子查询,但是如果有 5 个新闻具有最高优先级并且只从中获取 3 个但第 4 个或第 5 个具有最新的开始日期怎么办。
如果使子查询返回所有具有最大优先级的记录,可能只返回 2 个新闻或 1 个,而我需要 3 个。
我的问题的例子,这些记录:
Title:first, startDate:today, priority: 5
Title:second , startDate:today, priority: 5
Title:third , startDate:today, priority: 5
Title:fourth, startDate:today, priority: 5
Title:fifth, startDate:today, priority: 4
Title:sixth, startDate:tomorrow, priority: 4
我需要选择第一、第二和第三。 谢谢。
最佳答案
您可以在不使用子查询的情况下按多列排序。
SELECT *
FROM news
ORDER BY priority DESC, startDate DESC
LIMIT 3
当第一列出现平局时使用第二列。
关于mysql - SQL查询得到3个优先级最高的News,如果超过3个则根据startDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48651823/