【问题标题】:Database Trigger Insert from other table数据库触发器从其他表插入
【发布时间】:2018-01-30 20:23:49
【问题描述】:

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

sgr_customer 中插入新记录后,id_customersgr_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

非常感谢。

【问题讨论】:

  • 你有什么问题?
  • 我已经编写了该代码,但在插入 sgr_customer 表后,在 sgr_customer_group 表中没有完成任何操作(添加了任何新行)。触发代码有什么问题?
  • (1) 我不确定您是否需要“存在”检查;如果插入未成功完成,我认为 AFTER INSERT 触发器不会执行。 (2) 您插入的 VALUES 未指定 NEW.id_customer。 (3)@id_exists与DECLAREd id_exists不一样;前者是一个“会话”变量,它将在执行之间(在该连接上)保存它的值,后者是一个你从未真正引用过的局部变量。

标签: mysql triggers


【解决方案1】:

@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 ;

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多