简体   繁体   中英

MySQL Finding intersection where 2 entered dates intersect between a start_date and end_date

I am trying to find if 2 entered dates have an intersection between a start date/time and end date/time.

Example in my database table "reservation" we have a row(s) with the following

start_date = 2022-02-28 09:00:00 end_date = 2022-02-28 11:00:00

I would like to build a query where i can select this row when i pass in the following inputs

start date = 2022-02-28 08:30:00 end date = 2022-02-28 12:30:00

Now this filter should select any rows where the date/time intersect with it. I built the below query, however, this does not select the intersection that i want. Is there anything i can do to adjust the below query? This query works for the most part (when dates are truly inside the start/end date) but does not do any intersection like this. This query works for the most part but just not this scenario.

SELECT
    rp.product_id
FROM
    reservation r
    INNER JOIN reservation_product AS rp ON r.reservation_id = rp.reservation_id
WHERE
    (
        '2022-02-28 08:30:00' BETWEEN r.start_date
        AND r.end_date
    )
    OR (
        '2022-02-28 12:30:00' BETWEEN r.start_date
        AND r.end_date
    )

Example Data - The below inputs should select that row in the square.

start date = 2022-02-28 08:30:00 end date = 2022-02-28 12:30:00

在此处输入图像描述

You can find intersections if start_date<\/code> is less than the max of the 2 dates and end_date<\/code> is greater than the min of the 2 dates:

WHERE r.end_date >= '2022-02-28 08:30:00'
  AND r.start_date <= '2022-02-28 12:30:00'

The intervals A and B intersection condition is A.start<=B.End AND B.start <= A.End

.. 
WHERE
    (
        '2022-02-28 08:30:00' < r.end_date
    )
    AND (
        '2022-02-28 12:30:00' > r.start_date
    )

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