2

我有这张表(和一些记录)

 ------------ --------------------- 
| 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 以获得该结果?

4

1 回答 1

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'
);
于 2013-06-12T16:47:05.433 回答