我正在尝试创建触发器将主键分成两组。
这是我的表:
CREATE TABLE `q_locations` (
`id` int(11) NOT NULL,
`name` varchar(300) NOT NULL,
`standalone` bit(1) NOT NULL DEFAULT b'0',
UNIQUE KEY `id` (`id`),
KEY `standalone` (`standalone`)
)
如果standalone为0,则id应从1开始,如果standalone = 1,则id应从1000开始。每次插入后,Id应该递增。
我的触发器:
DELIMITER $$
CREATE TRIGGER trigger_insert_q_locations
BEFORE INSERT ON q_locations
FOR EACH ROW
BEGIN
SET New.id = (
SELECT coalesce(max(id) + 1, (case when standalone = 0 then 1 else 1000 end))
FROM q_locations
WHERE standalone = NEW.standalone);
END;
更新:所以在我得到的帮助下,我设法插入触发器而没有任何错误,当我更新我的位置表时,触发器没有做任何事情。值只是保持递增为默认值。
答案 0 :(得分:1)
尝试:
SET NEW.id = (SELECT coalesce(...) ...)
也许SELECT INTO在使用NEW-Aliases的更新触发器中无法正常工作。
更新:
这应该有效:
DELIMITER $$
CREATE TRIGGER trigger_insert_q_locations
BEFORE INSERT ON q_locations
FOR EACH ROW
BEGIN
DECLARE currentid INT;
SET currentid = (SELECT max(id) FROM q_locations WHERE standalone = NEW.standalone);
IF NEW.standalone = 0 THEN
SET NEW.id = coalesce(currentid + 1, 1);
ELSE
SET NEW.id = coalesce(currentid + 1,1000);
END IF;
END;