我有一个具有以下设置的表:
CREATE TABLE IF NOT EXISTS `appointment` (
`appId` tinyint(3) UNSIGNED AUTO_INCREMENT NOT NULL,
`startDateTime` datetime,
`duration` time DEFAULT NULL
);
示例数据:
appId startDateTime duration
1 2015-05-04 16:15:00 00:14:00
2 2015-05-12 08:15:00 05:54:00
3 2015-05-12 08:35:00 02:14:00
4 2016-05-04 08:11:00 04:11:00
5 2015-05-13 19:30:00 02:50:00
预期输出:
appId startDateTime duration
2 2015-05-12 08:15:00 05:54:00
3 2015-05-12 08:35:00 02:14:00
我需要一个能够检查表中的每个条目并返回冲突条目的查询。在上面的示例数据中,2 和 3 会重叠。我可以将两个字段都转换为 unix 时间并计算结束时间,但是我不确定如何比较每个条目
有什么想法吗?
最佳答案
使用 Faisal 的 fiddle ......
-- ----------------------------
-- Table structure for appointment
-- ----------------------------
DROP TABLE IF EXISTS `appointment`;
CREATE TABLE `appointment` (
`appId` tinyint(10) NOT NULL AUTO_INCREMENT,
`startDateTime` datetime DEFAULT NULL,
`duration` time DEFAULT NULL,
PRIMARY KEY (`appId`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of appointment
-- ----------------------------
INSERT INTO `appointment` VALUES
('1', '2015-05-04 16:15:00', '00:14:00'),
('2', '2015-05-12 08:15:00', '05:54:00'),
('3', '2015-05-12 08:35:00', '02:14:00'),
('4', '2016-05-04 08:11:00', '04:11:00'),
('5', '2015-05-13 19:30:00', '02:50:00');
SELECT DISTINCT x.*
FROM appointment x
JOIN appointment y
ON y.startdatetime < x.startdatetime + INTERVAL TIME_TO_SEC(x.duration) SECOND
AND y.startdatetime + INTERVAL TIME_TO_SEC(y.duration) SECOND > x.startdatetime
AND y.appid <> x.appid;
appId startDateTime duration
3 12.05.2015 08:35:00 02:14:00
2 12.05.2015 08:15:00 05:54:00
关于MySQL 选择日期时间重叠条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40832397/