How to find matching time intervals for more than 2 users

后端 未结 5 1676
自闭症患者
自闭症患者 2021-02-10 06:42

Find best suitable time from given time interval of different users.

Rows: 5
fid  userid  FromDateTime           ToDateTime          flag
62   1   2012-07-18 01:         


        
5条回答
  •  攒了一身酷
    2021-02-10 07:42

    Using sel's schema from the fiddle (10x sel)...

    The simplest way too do this is:

    SELECT
        MAX(GREATEST(u1.datetime_start, u2.datetime_start)) AS MeetingStart,
        MIN(LEAST(u1.datetime_end, u2.datetime_end)) AS MeetingEnd
    FROM users2 u1
    INNER JOIN users2 u2
        ON (u1.datetime_end >= u2.datetime_start AND u1.datetime_start <= u2.datetime_end)
        AND u2.userid != u1.userid
        AND u2.userid IN (3,4,5)
    WHERE u1.userid=2
    GROUP BY u1.id
    HAVING COUNT(DISTINCT u2.userid) = 3 AND MeetingStart < MeetingEnd
    

    Change according to your situation:

    In my example we have 4 participants. n=4, participants (2,3,4,5)

    IN (3,4,5) --> last n-1 id's of participants to the meeting

    WHERE u1.userid=2 --> id for the first participant to the meeting

    HAVING COUNT(DISTINCT u2.userid) = 3 --> n - 1

    Can be tested on sqlfiddle

提交回复
热议问题