2016-11-27 100 views
1

我有以下设置的表: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时间并计算结束时间,但我不确定如何比较每个条目

任何想法?

+0

你有什么样的数据?并告诉我们您的预期产出。 – Faisal

+0

如果事件A在事件B开始后结束,并且在事件B结束之前开始,则可以说事件A与事件B重叠。 – Strawberry

+0

@Faisal完成,谢谢 –

回答

1

使用费萨尔的小提琴......

-- ---------------------------- 
-- 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

+0

什么是“y.appid <> x.appid;”在做什么? –

+0

它忽略了自身重叠的事件。 – Strawberry

0

请尝试以下查询。希望它能解决你的问题。

SELECT 
    tbl1.* 
FROM 
    appointment tbl1, 
    appointment tbl2 
WHERE 
    tbl2.appId <> tbl1.appId 
AND tbl2.startDateTime < tbl1.startDateTime + INTERVAL TIME_TO_SEC(tbl1.duration) SECOND 
AND tbl2.startDateTime + INTERVAL TIME_TO_SEC(tbl2.duration) SECOND > tbl1.startDateTime; 

通过点击下面的链接,你可以看到你想要的预期结果。

SQL Fiddle Demo

+0

我怀疑它不知何故 – Strawberry

+0

@strawberry你为什么怀疑?你能解释一下吗? – Faisal

+0

仅仅是因为在psame日发生了两件事情,并不意味着它们重叠 – Strawberry