MySQL 选择日期时间重叠条目

标签 mysql

我有一个具有以下设置的表:

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

http://rextester.com/YJA59081

关于MySQL 选择日期时间重叠条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40832397/

相关文章:

MySQL REPLACE 语句不正确? "A new statement was found, but no delimiter"

mysql - 如果其他表中不存在 id,则获取不同的行并使用合并

java - Birt 报告重复行 - 表

php - 验证密码返回 0 行,而预期返回 1 行

php - 如何在php中查看其他用户的个人资料?

php - 如何使用 PHP 在同一个 SQL 列中存储多条记录?

php - 提交空白值并返回 mysql 查询的问题

c# - SQL参数编辑

mysql - 优化返回数百条记录的 Rails 3.0 查询

sql - 匹配 ... 针对更多字段 : give more importance to first field?