数据库触发器从其他表插入

时间:2018-01-30 20:23:50

标签: mysql triggers

我有两张桌子,如下所述。我做了一个触发器,在sgr_customer_group表中新插入后必须在sgr_customer表上执行:

sgr_customer中添加新内容后,必须将id_customer(主键为sgr_customer)和常量4的新记录插入sgr_customer_group表中。

DELIMITER $$
CREATE TRIGGER sgr_customer_trig
AFTER INSERT ON `sgr_customer` FOR EACH ROW
begin
       DECLARE id_exists Boolean;

       SELECT 1
       INTO @id_exists
       FROM sgr_customer
       WHERE sgr_customer.id_customer= NEW.id_customer;

       IF @id_exists = 1
       THEN
           Insert into sgr_customer_group (id_customer, id_group)VALUES(id_customer,4);
        END IF;
END
$$
DELIMITER ;

表定义:

sgr_customer_group(id_group,id_customer#,id_group );
id_group:Primary Key
sgr_customer(id_customer,......); 
id_customer:Primary key

非常感谢。

1 个答案:

答案 0 :(得分:0)

@Uueerdo在他们的评论中对您的问题所做的一切都是正确的,因此可以将触发器简化为:

DELIMITER $$
CREATE TRIGGER sgr_customer_trig
AFTER INSERT ON `sgr_customer` FOR EACH ROW
BEGIN
   INSERT INTO sgr_customer_group (id_customer, id_group) VALUES(NEW.id_customer, 4);
END
$$
DELIMITER ;