【问题标题】:MySQL before insert trigger that drops insert if conditionMySQL在插入触发器之前删除插入条件
【发布时间】:2019-07-30 02:10:50
【问题描述】:

我有以下表格:

slds:

+-----------+-----------+
|    id     | sld_name  |  
+-----------+-----------+
|     1     |  google   |  
+-----------+-----------+
|     2     |  github   |
+-----------+-----------+

路径:

+-----------+------------+----------+
|    id     | path_name  |  sld_id  |   
+-----------+------------+----------+
|    101    |  /cats/    |    1     |
+-----------+------------+----------+
|    102    |  /dogs/    |    2     |
+-----------+------------+----------+

注意sld_name是唯一索引,sld_idslds的外键。

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 ;

所有这一切都是为了防止插入发生。

触发器是否存在特定问题?还是这种策略一般都行不通?

有没有更好的方法来解决这个问题?

任何建议都将不胜感激! :)

【问题讨论】:

    标签: mysql sql sql-insert database-trigger unique-constraint


    【解决方案1】:

    您可以简单地在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 KEYIGNORE 更安全,因为它只捕获重复键错误,而IGNORE 基本上将 any 错误变成警告(数据类型错误,NULL 值不可为空列,...)。

    【讨论】:

      【解决方案2】:

      如果您向两个表都添加了主键和外键关系,并且还向表添加了唯一约束。在insert 之后删除ignore。 然后foreign key and unique key 关系将帮助您停止添加重复项。希望它会帮助你。谢谢

      【讨论】:

        猜你喜欢
        • 2016-07-12
        • 2017-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-11
        相关资源
        最近更新 更多