选择日期时间记录范围,同时包括范围之外的最后记录

时间:2013-06-12 16:34:18

标签: mysql

我有这张桌子(以及一些记录)

 ------------ --------------------- 
| id         | date_time           |
 ------------ --------------------- 
|    2489143 | 2013-05-31 00:00:00 | 
|    2489144 | 2013-05-31 00:30:00 | 
|    2489145 | 2013-05-31 01:00:00 | 
|    2489146 | 2013-05-31 01:30:00 | 
|    2489147 | 2013-05-31 02:00:00 | 
|    2489148 | 2013-05-31 02:30:00 | 
|    2489149 | 2013-05-31 03:00:00 | 
|    2489150 | 2013-05-31 03:30:00 | 
|    2489151 | 2013-05-31 04:00:00 | 
|    2489152 | 2013-05-31 05:00:00 | 
 ------------ --------------------- 
10 rows in set (0.01 sec)

我希望在一个时间范围之间获得记录,但是,我想在时间范围之外获得最后一条记录,例如:

select id, date_time 
from t1 
where date_time >= '2013-05-31 01:15:00' 
    && date_time <= '2013-05-31 02:20:00';

我明白了:

 ------------ --------------------- 
| id         | date_time           |
 ------------ --------------------- 
|    2489146 | 2013-05-31 01:30:00 | 
|    2489147 | 2013-05-31 02:00:00 | 
 ------------ --------------------- 

但我想要这个:

 ------------ --------------------- 
| id         | date_time           |
 ------------ --------------------- 
|    2489145 | 2013-05-31 01:00:00 | 
|    2489146 | 2013-05-31 01:30:00 | 
|    2489147 | 2013-05-31 02:00:00 | 
 ------------ --------------------- 

如何查询MySQL以获得该结果?

1 个答案:

答案 0 :(得分:3)

您可以使用UNION子句获得所需的结果:

(
    SELECT id, date_time
    FROM t1
    WHERE date_time < '2013-05-31 01:15:00'
    ORDER BY date_time DESC
    LIMIT 1
)
UNION ALL
(
    SELECT id, date_time 
    FROM t1 
    WHERE date_time BETWEEN '2013-05-31 01:15:00'
        AND '2013-05-31 02:20:00'
);