0

I want to create a query that inserts data to a table and checks if my date range overlaps the already existing date ranges.

I created the following working query but it inserts 2 rows with the same data. Can you find anything wrong in it?

INSERT INTO infoscreen_times (screen_id, start, end, view_id)
SELECT ?, ?, ?, ?
FROM infoscreen_screens
WHERE EXISTS (
    SELECT id
    FROM infoscreen_times
    WHERE ? BETWEEN start AND end
    AND screen_id = ?
    OR ? BETWEEN start AND end
    AND screen_id = ?
    OR ? <= start
    AND ? >= end
    AND screen_id = ?) IS FALSE

start means the Start-Timestamp, end is the End-Timestamp. In the Subquery i want the check if the timestamps i want to insert overlap each other. If they do i want to get a error and if they dont the query insert the data.

Thanks in advance.

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
Joshua H.
  • 87
  • 1
  • 10

3 Answers3

1

I believe this is the logic you want. Most importantly, you want not exists. Secondarily, you need to get the date arithmetic correct:

INSERT INTO infoscreen_times (screen_id, start, end, view_id)
    SELECT ?, ?, ?, ?
    FROM infoscreen_screens iss
    WHERE NOT EXISTS (SELECT 1
                      FROM infoscreen_times ist
                      WHERE ist.screen_id = iss.screen_id AND
                            ? <= ist.end AND -- ? is the begin time
                            ? >= ist.begin   -- ? is the end time
                     );
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You need an SQL expression that generates a boolean depending on whether or not one date range overlaps another. See this SO answer

What you're using does not seem correct. I can't diagnose exactly why, or suggest a better query without knowing the table schema. Can you post that?

Community
  • 1
  • 1
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
0

You should use parentheses to distinct different parts of OR operators. I think the answer is:

INSERT INTO infoscreen_times (screen_id, start, end, view_id) 
SELECT ?, ?, ?, ? 
FROM infoscreen_screens 
WHERE EXISTS (SELECT id FROM infoscreen_times WHERE (? BETWEEN start AND end AND screen_id = ?) OR (? BETWEEN start AND end AND screen_id = ?) OR (? <= start AND ? >= end AND screen_id = ?)) 
IS FALSE

However, I don't know the meaning of these question marks in MySql. :)

Mehdi Javan
  • 1,081
  • 6
  • 25