SQL Query to show nearest date?(SQL查询显示最近的日期?)
问题描述
我想弄清楚如何编写一个 MySQL 查询,该查询将返回最接近日期的 3 个事件.
I'm trying to figure out how to write a MySQL query that will return the closest 3 events in terms of date.
这是我的桌子:
EVENT_ID EVENT_NAME EVENT_START_DATE(DATETIME)
1 test 2011-06-01 23:00:00
2 test2 2011-06-03 23:00:00
3 test3 2011-07-01 23:00:00
4 test4 2011-08-09 23:00:00
5 test5 2011-06-02 23:00:00
6 test6 2011-04-20 23:00:00
因此查询结果应该是 ID 的 1,2,5,因为它们与当前日期相比最接近发生..
So the query result should be for ID's 1,2,5 as they are the closest to occur in comparison to the current date..
查询应该只找到未来的事件.
query should find only future events.
推荐答案
SELECT event_id
FROM Table
ORDER BY ABS( DATEDIFF( EVENT_START_DATE, NOW() ) )
LIMIT 3
ABS()
表示 1 天前的事件与未来 1 天的事件一样接近.如果您只想要尚未发生的事件,请执行
The ABS()
means that an event 1 day ago is just as close as an event 1 day in the future. If you only want events that haven't happened yet, do
SELECT event_id
FROM Table
WHERE EVENT_START_DATE > NOW()
ORDER BY EVENT_START_DATE
LIMIT 3
这篇关于SQL查询显示最近的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL查询显示最近的日期?


基础教程推荐
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01