我有下表:
slds:
+-----------+-----------+
| id | sld_name |
+-----------+-----------+
| 1 | google |
+-----------+-----------+
| 2 | github |
+-----------+-----------+
路径:
+-----------+------------+----------+
| id | path_name | sld_id |
+-----------+------------+----------+
| 101 | /cats/ | 1 |
+-----------+------------+----------+
| 102 | /dogs/ | 2 |
+-----------+------------+----------+
请注意,sld_name
是唯一索引,sld_id
是slds
的外键。
INSERT IGNORE INTO paths (path_name, sld_id)
VALUES ('/dogs/', 1), ('/dogs/', 2) ... this can be hundreds of rows long
当上面的示例发生时,我需要一种方法来删除/阻止插入额外的 ('/dogs/', 2)
行,因为该路径已经存在于 sld_id 处=2
,并且不会阻止 ('/dogs/', 1)
行,因为 sld_id=1
没有 /dogs/
路径尚未。
为了实现这一点,我尝试使用此触发器:
delimiter $$
create trigger after_insert_paths
after insert on paths
for each row begin
declare path_check INT;
set path_check := (
select sld_id
from paths
where path_name=new.path_name and sld_id=new.sld_id
);
if path_check is not null then
set new.path_name = null;
end if;
end $$
delimiter ;
这一切都是为了阻止插入的发生。
触发器是否存在特定问题?还是这个策略一般不起作用?
我缺少更好的方法吗?
如有任何建议,我们将不胜感激! :)
最佳答案
您可以简单地在 paths(path_name, sld_id)
上创建一个 UNIQUE
键:
ALTER TABLE paths ADD UNIQUE paths_idx(path_name, sld_id);
现在,当尝试插入重复项时,MySQL 将引发错误,您可以使用 ON DUPLICATE KEY UPDATE
feature 来处理该错误。 :
INSERT INTO paths (path_name, sld_id) VALUES ('/dogs/', 1)
ON DUPLICATE KEY UPDATE sld_id = sld_id;
ON DUPLICATE KEY
比 IGNORE
更安全,因为它只捕获重复键错误,而 IGNORE
基本上会变成 any 错误变成警告(数据类型错误,不可为空列中的 NULL
值,...)。
关于MySQL before insert 触发器,删除 insert if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056518/