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 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
