我有一个mysql查询问题

时间:2017-12-11 06:08:04

标签: mysql

我的MySQL查询在22:29:50正常但是在22:30:00之后,end_time是第二天07:29:59查询无效。

MY TABLE换班

shift_name |start_time | end_time
shift1     | 07:30:00  |15:30:00
shift2     | 15:30:00  | 22:30:00
shift3     | 22:30:00  | 07:30:00

我写了以下查询

select shift_name from shift 
where time('22:30:00') BETWEEN start_time and end_time;

1 个答案:

答案 0 :(得分:1)

CREATE TABLE shift 
    (`shift_name` varchar(6), `start_time` time, `end_time` time);
     

INSERT INTO shift 
    (`shift_name`, `start_time`, `end_time`)
VALUES
    ('shift1', '07:30:00', '15:30:00'),
    ('shift2', '15:30:00', '22:30:00'),
    ('shift3', '22:30:00', '07:30:00');
     

select 
     *
from (
     select cast('05:22' as time) t
    ) d
cross join shift
where (t >= start_time and t < end_time) 
or  (t >= cast('00:00' as time) and t < end_time and start_time > end_time ) 
or  (t >= start_time and start_time > end_time )
t        | shift_name | start_time | end_time
:------- | :--------- | :--------- | :-------
05:22:00 | shift3     | 22:30:00   | 07:30:00
select 
     *
from (
     select cast('23:52' as time) t
    ) d
cross join shift
where (t >= start_time and t < end_time) 
or  (t >= cast('00:00' as time) and t < end_time and start_time > end_time ) 
or  (t >= start_time and start_time > end_time )
t        | shift_name | start_time | end_time
:------- | :--------- | :--------- | :-------
23:52:00 | shift3     | 22:30:00   | 07:30:00
select 
     *
from (
     select cast('10:52' as time) t
    ) d
cross join shift
where (t >= start_time and t < end_time) 
or  (t >= cast('00:00' as time) and t < end_time and start_time > end_time ) 
or  (t >= start_time and start_time > end_time )
t        | shift_name | start_time | end_time
:------- | :--------- | :--------- | :-------
10:52:00 | shift1     | 07:30:00   | 15:30:00
select 
     *
from (
     select cast('19:52' as time) t
    ) d
cross join shift
where (t >= start_time and t < end_time) 
or  (t >= cast('00:00' as time) and t < end_time and start_time > end_time ) 
or  (t >= start_time and start_time > end_time )
t        | shift_name | start_time | end_time
:------- | :--------- | :--------- | :-------
19:52:00 | shift2     | 15:30:00   | 22:30:00

dbfiddle here