In MySQL, you can use self-join to get the end time of the previous record and the start time of the next record and combine them into one record. First, you need to create a temporary table containing record ID and time information for the table, and then use a self-join to obtain the time information of adjacent records.
data preparation:
-- demo.schedule definition
CREATE TABLE `schedule` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`start_time` datetime NOT NULL,
`end_time` datetime NOT NULL,
`employee_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
INSERT INTO demo.schedule
(start_time, end_time, employee_id)
VALUES('2023-09-08 07:50:00', '2023-09-08 12:00:00', 1);
INSERT INTO demo.schedule
(start_time, end_time, employee_id)
VALUES('2023-09-08 12:40:00', '2023-09-08 17:20:00', 1);
INSERT INTO demo.schedule
(start_time, end_time, employee_id)
VALUES('2023-09-08 18:10:00', '2023-09-08 20:30:00', 1);
The following is a sample query, assuming your table is named schedule, which contains the id, start_time, and end_time fields:
select * from schedule;
Output:
-- 创建临时表并插入数据
CREATE TEMPORARY TABLE temp_schedule (
prev_id INT,
curr_id INT,
prev_end_time DATETIME,
curr_start_time DATETIME
);
INSERT INTO temp_schedule (prev_id, curr_id, prev_end_time, curr_start_time)
SELECT
t1.id AS prev_id,
t2.id AS curr_id,
t1.end_time AS prev_end_time,
t2.start_time AS curr_start_time
FROM
schedule t1
JOIN
schedule t2 ON t1.id = t2.id - 1;
select * from temp_schedule
Output:
This query will create a temporary table called temp_schedule that contains the IDs of adjacent records, the end time of the previous record, and the start time of the next record. Finally, the result of selecting the end time of the previous record and the start time of the next record is selected by executing the query on the temporary table.
Note : This query assumes that the records are in chronological order and that each record's ID is unique. If your table structure or data does not meet these requirements, you need to make adjustments based on the actual situation.