我有mysql表
CREATE TABLE `range` (
`id` int(11) NOT NULL,
`object_id` int NOT NULL,
`datetime_from` datetime NOT NULL,
`datetime_to` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
请帮助提供关于mysql级别约束的实现:没有相同object_id的时间间隔交集。
答案 0 :(得分:0)
触发器很好,但是为了证明不需要触发器,请考虑以下内容......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (
id SERIAL,
dt_from DATE NOT NULL,
dt_to DATE NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO my_table (dt_from,dt_to)
VALUES
('2018-05-31','2018-06-03');
- 尝试1:冲突日期
SET @dt_from = '2018-05-28';
SET @dt_to = '2018-06-01';
INSERT INTO my_table (dt_from,dt_to)
SELECT @dt_from
, @dt_to
FROM (SELECT 1) x
LEFT
JOIN my_table y
ON y.dt_from < @dt_to
AND y.dt_to > @dt_from
WHERE y.id IS NULL;
- 尝试2:无冲突的日期
SET @dt_from = '2018-06-04';
SET @dt_to = '2018-06-06';
INSERT INTO my_table (dt_from,dt_to)
SELECT @dt_from
, @dt_to
FROM (SELECT 1) x
LEFT
JOIN my_table y
ON y.dt_from < @dt_to
AND y.dt_to > @dt_from
WHERE y.id IS NULL;
SELECT * FROM my_table;
+----+------------+------------+
| id | dt_from | dt_to |
+----+------------+------------+
| 1 | 2018-05-31 | 2018-06-03 |
| 2 | 2018-06-04 | 2018-06-06 |
+----+------------+------------+
请参阅。冲突的日期将被忽略。