简体   繁体   中英

Sequelize query for overlapping events

I am trying to make a findAll() query using Sequelize that does the following. I want to be able to enter a user's ID and search the Events table to find if any other users' events overlap with any of the chosen user's events. I want to make sure that the events overlap by at least 30 mins.

Events table
id     start                  end                    createdByUser
1      2020-08-17 05:00:00    2020-08-17 08:00:00    1
2      2020-08-17 06:00:00    2020-08-17 11:00:00    2
3      2020-08-17 07:00:00    2020-08-17 11:00:00    3
4      2020-08-18 12:00:00    2020-08-18 13:00:00    1
5      2020-08-18 12:50:00    2020-08-18 14:00:00    2
6      2020-08-18 09:00:00    2020-08-18 12:10:00    3
7      2020-08-18 12:00:00    2020-08-18 12:45:00    4
8      2020-08-18 15:00:00    2020-08-18 18:00:00    2

Example: I want to be able to say "look at all of User 1's events. See if any other users' events overlap with any of User 1's events by at least 30 mins." If the returned query data could somehow note which of User 1's events it overlaps with that would be even better: Something like the following:

{id: 2,
 start: 2020-08-17 06:00:00,
 end: 2020-08-17 11:00:00,
 createdByUser: 2,
 overlapWithEventID: 1
},
{id: 3,
 start: 2020-08-17 07:00:00,
 end: 2020-08-17 11:00:00,
 createdByUser: 3,
 overlapWithEventID: 1
},
{id: 7,
 start: 2020-08-18 12:00:00,
 end: 2020-08-18 12:45:00,
 createdByUser: 4,
 overlapWithEventID: 4
}

Thanks in advance for the help. This is a way more complex query than I am used to making.

SELECT t2.*, t1.id overlapWithEventID
FROM events t1
JOIN events t2
WHERE t1.createdByUser = 1
  AND t2.createdByUser != 1
  AND TIMESTAMPDIFF(MINUTE, GREATEST(t1.start, t2.start), LEAST(t1.`end`, t2.`end`)) >= 30;

fiddle

Adjust to DBMS which you're using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM