我想创建一个查询,将数据插入表中并检查我的日期范围是否与现有的日期范围重叠。
我创建了以下工作查询,但它插入了具有相同数据的 2 行。你能发现其中有什么问题吗?
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 表示开始时间戳,end 表示结束时间戳。在子查询中,我想检查我想要插入的时间戳是否彼此重叠。如果他们这样做,我想得到一个错误,如果他们不这样做,则查询插入数据。
提前致谢。
最佳答案
我相信这就是你想要的逻辑。最重要的是,您希望不存在
。其次,您需要使日期算术正确:
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
);
关于MySQL 插入语句双条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37464473/