mysql怎么查询两个时间段分别最近的一条数据

例如,开始时间:2022-02-20 9:00 结束时间:2022-02-21 11:00
第一条数据查询离 开始时间 最近的一条记录,开始时间往下最近一条。

第二条数据查询离 结束时间 最近的一条记录,结束时间往下最近的一条。

得到结果:分别最近的两条数据是 2022-02-20 8:30、2022-02-21 10:59

我找了一个解决办法

img


不知道还有什么地方可以优化的吗?

表中的数据内容大概是什么样子的?

例如,开始时间:2022-02-20 9:00 结束时间:2022-02-21 11:00
这个时间是传入的条件吗?还是其他的表中的数据,需要关联的?
如果只是找最近的时间的话,可以将子查询放入where 条件中,然后输出就可以了,如果是其他的情况的话,需要看一下具体的数据内容是什么样子了,如果需要继续探究的话,回复评论即可。

select * from table_a 
where time_col = 
       (select max(time_col ) from table_a 
        where time_col <= '2022-02-20 9:00')

分两次查,伪代码

where 时间 小于 '2022-02-20 9:00' order by 时间 倒序 limit 1
where 时间 小于 '2022-02-21 11:00' order by 时间 倒序 limit 1

如果你想一条一条的查就可以这样

select * from 表名 where 时间字段 < ‘具体时间’ order by 时间字段 desc limit 1

如果你想传入开始时间和结束时间,返回两条结果可以这样

(select * from 表名 where 时间字段<'开始时间' ORDER BY 时间字段 desc limit 1)
union 
(select * from 表名 where 时间字段>'开始时间' and 时间字段<'结束时间' ORDER BY 时间字段 desc limit 1)

这题应该尽量避免order by

select max(a.daydate),min(a.daydate) 
from 
table a,
(select max(daydate) max_date,min(daydate) min_date from table) b
where 
a.daydate < b.max_date
and a.daydate > b.min_date
;
```sql


```