这是我第一次使用触发器,我遇到了一些麻烦。
我创建了一个通知系统,当创建新通知时,它会向notify
表添加一行。添加的内容取决于它的通知类型。
到目前为止,我已尝试过:
DELIMITER $$
DROP TRIGGER IF EXISTS generate_notify $$
CREATE TRIGGER generate_notify
AFTER INSERT
ON notifications
FOR EACH ROW
BEGIN
SELECT @group := notify_group FROM notification_types WHERE type=NEW.type;
IF (@group <> 1) THEN
INSERT INTO notify (user_id, notification_id) VALUES (NEW.user_reference, NEW.id);
ELSE
INSERT INTO notify (user_id, notification_id) VALUES(
SELECT ID, NEW.id FROM user_customer WHERE clientID=NEW.user_reference
);
END IF;
END; $$
DELIMITER ;
我四处搜索,然后将其更改为:
DELIMITER $$
DROP TRIGGER IF EXISTS generate_notify $$
CREATE TRIGGER generate_notify
AFTER INSERT
ON notifications
FOR EACH ROW
BEGIN
DECLARE insert_user_id INT(11);
SELECT @group := notify_group FROM notification_types WHERE type=NEW.type;
IF (@group <> 1) THEN
INSERT INTO notify (user_id, notification_id) VALUES (NEW.user_reference, NEW.id);
ELSE
SELECT ID INTO insert_user_id FROM user_customer WHERE clientID=NEW.user_reference;
INSERT INTO notify (user_id, notification_id) VALUES(insert_user_id, NEW.id);
END IF;
END; $$
DELIMITER ;
我也尝试过将上面的内容混合起来,所有我得到的都是无法返回结果集,或者我的选择查询存在语法错误。
(另外,我假设为触发器预定义了NEW
关键字?)
答案 0 :(得分:1)
您的第一次尝试实际上是在正确的轨道上,但您没有将SELECT
的结果写入变量。无法从触发器返回结果集。
DELIMITER $$
DROP TRIGGER IF EXISTS generate_notify $$
CREATE TRIGGER generate_notify
AFTER INSERT
ON notifications
FOR EACH ROW
BEGIN
DECLARE v_group INT;
SELECT notify_group INTO v_group FROM notification_types WHERE type=NEW.type;
IF (v_group <> 1) THEN
INSERT INTO notify (user_id, notification_id) VALUES (NEW.user_reference, NEW.id);
ELSE
INSERT INTO notify (user_id, notification_id) VALUES(
SELECT ID, NEW.id FROM user_customer WHERE clientID=NEW.user_reference
);
END IF;
END $$
DELIMITER ;