【发布时间】:2018-01-30 20:23:49
【问题描述】:
我有两张表,如下所述。我创建了一个触发器,在新插入sgr_customer 表后必须在sgr_customer_group 表上执行:
在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
非常感谢。
【问题讨论】:
-
你有什么问题?
-
我已经编写了该代码,但在插入 sgr_customer 表后,在 sgr_customer_group 表中没有完成任何操作(添加了任何新行)。触发代码有什么问题?
-
(1) 我不确定您是否需要“存在”检查;如果插入未成功完成,我认为 AFTER INSERT 触发器不会执行。 (2) 您插入的 VALUES 未指定 NEW.id_customer。 (3)
@id_exists与DECLAREdid_exists不一样;前者是一个“会话”变量,它将在执行之间(在该连接上)保存它的值,后者是一个你从未真正引用过的局部变量。