MySQL - Finding time overlaps

前端 未结 2 1935
忘了有多久
忘了有多久 2021-01-12 21:57

I have 2 tables in the database with the following attributes:

Booking
=======
booking_id
booking_start
booking_end

resource_booked
===============
booking_         


        
相关标签:
2条回答
  • 2021-01-12 22:40

    Wow! I would have never thought of that.. I didn't expect such detailed assistance either, thanks a bunch for all the effort you've put into it! I'm trying to understand and learn from your query :>

    The bookings table has another attribute called creation_date which shows when the booking was made and I was hoping to only show the booking (with overlap in time or clashes) that was made later. So it'd be:

    Booking 1 
    =========
    creation_date - 2000-01-01 13:00:00
    booking_start - 2000-02-24 12:00:00
    booking_end   - 2000-02-24 14:00:00
    
    Booking 2 
    =========
    creation_date - 2000-01-02 15:00:00
    booking_start - 2000-02-24 13:00:00
    booking_end   - 2000-02-24 15:00:00
    

    There is a time overlap between booking 1 and 2 and since booking 2 was made a day later than booking 1, only booking 2 would be shown.

    0 讨论(0)
  • 2021-01-12 23:02

    EDIT: using additional info, this is now limited to showing only those bookings that clash with some EARLIER booking.

    I think this wll do the trick:

    SELECT DISTINCT
        b2.booking_id, -- The later booking
        b2.booking_start,
        b2.booking_end,
        b2.creation_date,
        rb1.resource_id, -- The resource over which the two bookings clash
        b1.booking_id, -- The earlier booking
        b1.booking_start,
        b1.booking_end
    FROM resource_booked rb1
        INNER JOIN booking b1 ON b1.booking_id = rb1.booking_id
        INNER JOIN booking b2 ON b1.booking_id <> b2.booking_id
            AND b2.booking_start BETWEEN b1.booking_start AND b1.booking_end
        INNER JOIN resource_booked rb2 ON rb2.resource_id = rb1.resource_id
            AND rb2.booking_id = b2.booking_id
    

    This is how it was tested:

    use tempdb
    
    drop table resource_booked 
    drop table Booking
    
    create table Booking
    (
        booking_id int,
        booking_start datetime,
        booking_end datetime,
        creation_date datetime
    )
    
    create table resource_booked 
    (
        booking_id int,
        resource_id int
    )
    
    insert Booking values (1, '1 january 2000', '1 march 2000', '1 january 2000')
    insert Booking values (2, '1 february 2000', '1 may 2000', '2 january 2000')
    insert Booking values (3, '1 april 2000', '1 june 2000', '3 january 2000')
    insert Booking values (4, '1 july 2000', '1 august 2000', '4 january 2000')
    
    insert resource_booked values (1, 1)
    insert resource_booked values (2, 1)
    insert resource_booked values (3, 1)
    insert resource_booked values (4, 1)
    insert resource_booked values (1, 2)
    insert resource_booked values (3, 2)
    
    0 讨论(0)
提交回复
热议问题