问题
I have the following table structure that has day wise shifts.
At only C shift, time is shared by two days.
As you can C Shift starts at 20:30 and ends the next's days 06:00.
The Table structure and data as follows
create table `machine_shifts` (
`date` date ,
`shift_start_time` time ,
`shift_end_time` time ,
`shift` varchar (60),
`updated_on` timestamp
);
insert into `machine_shifts` (`date`, `shift_start_time`, `shift_end_time`, `shift`, `updated_on`) values('2010-01-01','06:00:00','14:30:00','A','2020-01-29 15:37:26'),
('2010-01-01','14:30:00','22:30:00','B','2020-01-29 15:37:26'),
('2010-01-01','22:30:00','06:00:00','C','2020-01-29 15:37:26'),
('2010-01-02','06:00:00','14:30:00','A','2020-01-29 15:37:26'),
('2010-01-02','14:30:00','22:30:00','B','2020-01-29 15:37:26'),
('2010-01-02','22:30:00','06:00:00','C','2020-01-29 15:37:26'),
('2010-01-03','06:00:00','14:30:00','A','2020-01-29 15:37:26'),
('2010-01-03','14:30:00','22:30:00','B','2020-01-29 15:37:26'),
('2010-01-03','22:30:00','06:00:00','C','2020-01-29 15:37:26'),
('2010-01-04','06:00:00','14:30:00','A','2020-01-29 15:37:26'),
('2010-01-04','14:30:00','22:30:00','B','2020-01-29 15:37:26'),
('2010-01-04','22:30:00','06:00:00','C','2020-01-29 15:37:27');
The Data is represented as follows
Now what I wanted is, I want to retrieve the data between two given timelines which includes shift from the above data set. And I've this following query
SELECT * FROM machine_shifts
WHERE ((CONCAT(`date`, ' ', shift_start_time))
BETWEEN '2010-01-02 00:00:00' AND '2010-01-03 10:00:00')
OR (CONCAT(`date`, ' ', shift_end_time)
BETWEEN '2010-01-02 00:00:00' AND '2010-01-03 10:00:00')
ORDER BY `date`, shift_start_time ASC
With the above query, what I'm getting is
In the above fetched result set, the last row wasn't expected and shouldn't be displayed also I want to retrieve C shift of 2010-01-01 too in the first row even though I'm passing 2010-01-02 00:00:00 as it should fall under C shift of 2010-01-01.
This is the following result I'm expecting
How can I achieve it?
回答1:
Your query looks fine; you just need a little bit of conditional logic to adjust the end date for the ends of shift C.
This should do it:
SELECT * FROM machine_shifts
WHERE
CONCAT(`date`, ' ', shift_start_time)
BETWEEN '2010-01-02 00:00:00'
AND '2010-01-03 10:00:00')
OR CONCAT(`date`, ' ', shift_end_time) + INTERVAL (shift = 'C') DAY
BETWEEN '2010-01-02 00:00:00'
AND '2010-01-03 10:00:00'
ORDER BY `date`, shift_start_time ASC
The idea is to add one day to the computation when we met the end of a C shift. This is what expression + INTERVAL (shift = 'C') DAY
does.
Note that the nested parenthses around conditions are not needed here.
来源:https://stackoverflow.com/questions/60122785/not-getting-expected-results-with-the-query-ive-in-mysql