My general question seems to be answered by https://stackoverflow.com/a/3025332/3650835, but I do not fully understand it after reading the MySql docs and am wondering if my solution will work as I expect, and also wonder if LIMIT 1 is needed.
Goal: to ensure that, for a given user_id, start and end never "overlap". As an example:
test_table
user_id start end
4 1 5
4 6 13
4 11 17 --> NOT allowed, bc 11 <= 13
2 1 9 --> allowed, user_id is different
My current solution
/* this should not insert anything, as it would cause an "overlap" of start
and end, based on row 2 having end = 13 */
INSERT INTO `test_table` (user_id, start, end)
SELECT '4', '11', '17' FROM DUAL
WHERE NOT EXISTS (SELECT * FROM `test_table`
WHERE user_id = '4' AND end >= '11')
LIMIT 1;
Does the WHERE NOT EXISTS
section mean "only do this insert...if this following select returns nothing"?
Also, there was the following comment in the linked solution, but I do not understand why based on the MySql docs this would be true. If true, I could remove Limit 1 from my solution:
If you use "from dual" on line 2 instead of "from table", then you don't need the "limit 1" clause
Thanks for your time.
Edit: here is all the sql for testing/setup:
CREATE TABLE `test_table`(
`id` INT PRIMARY KEY AUTO_INCREMENT,
`user_id` INT,
`start` INT,
`end` INT
);
INSERT INTO `test_table` (user_id, start, end)
SELECT '4', '1', '5' FROM DUAL
WHERE NOT EXISTS (SELECT * FROM `test_table`
WHERE user_id = '4' AND end >= '1')
LIMIT 1;
INSERT INTO `test_table` (user_id, start, end)
SELECT '2', '1', '9' FROM DUAL
WHERE NOT EXISTS (SELECT * FROM `test_table`
WHERE user_id = '2' AND end >= '1')
LIMIT 1;
INSERT INTO `test_table` (user_id, start, end)
SELECT '4', '6', '13' FROM DUAL
WHERE NOT EXISTS (SELECT * FROM `test_table`
WHERE user_id = '4' AND end >= '6')
LIMIT 1;
/* this should not insert anything, as it would cause an "overlap" of start and end */
INSERT INTO `test_table` (user_id, start, end)
SELECT '4', '11', '17' FROM DUAL
WHERE NOT EXISTS (SELECT * FROM `test_table`
WHERE user_id = '4' AND end >= '11')
LIMIT 1;