Enayet Hussain
Enayet Hussain

Reputation: 1018

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?

Upvotes: 1

Views: 116

Answers (2)

Faisal
Faisal

Reputation: 4765

Try with this below query. Hope it should be solve your problem.

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;

By clicking on the below link you can see your expected result in live which you want.

SQL Fiddle Demo

Upvotes: 0

Strawberry
Strawberry

Reputation: 33935

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

Upvotes: 1

Related Questions