Enayet Hussain Enayet Hussain - 13 days ago 5
MySQL Question

MySQL Select Datetime Overlapping Entries

I have a table with the following setup:

CREATE TABLE IF NOT EXISTS `appointment` (
`appId` tinyint(3) UNSIGNED AUTO_INCREMENT NOT NULL,
`startDateTime` datetime,
`duration` time DEFAULT NULL
);


Sample Data:

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


Expected Output:

appId startDateTime duration
2 2015-05-12 08:15:00 05:54:00
3 2015-05-12 08:35:00 02:14:00


I need a query that is able to check every entry in the table and return and entries that collide. In the sample data above, 2 and 3 will overlap. I can convert both of the fields to unix time and calculate the end time however I am not sure how to compare each entry

Any idea?

Answer

Using Faisal's 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