创建触发器后更新数据时出现问题。触发器连接2个表(人和教堂),并应在教堂表中更新教堂名称时更新churchID。
我尝试将子查询放入set语句中,但出现另一个错误1093 ,该错误表示您无法在FROM
子句中指定目标表“ people”。
这是我的触发器
delimiter $$
CREATE TRIGGER churchID_update_change AFTER UPDATE ON people
FOR EACH ROW
BEGIN
IF NEW.church != OLD.church THEN
UPDATE people as p, (SELECT DISTINCT c.churchID
FROM churches c LEFT OUTER JOIN people p
ON c.name = p.church
WHERE NEW.church = c.name) as new_church
SET p.churchID = new_church
WHERE NEW.church = NEW.church;
END IF;
END
$$
delimiter ;
这是我要执行的更新:
UPDATE people
SET church = 'Efree'
WHERE firstname = 'Mark';
人员表具有以下字段:
教堂数据库是
我要使用此触发器进行的操作是,每当更改个人教堂时,它都会自动将churchID更改为在教堂表中排队的churchID
例如,如果您这样做
SELECT churchID
FROM churches
WHERE name = 'federated';
它将返回1的churchID,或者如果返回则返回
`SELECT churchID`
FROM churches
WHERE name = 'EFree'
它将返回6的churchID
因此,我现在要执行更新,它应该返回Mark的“ firstname”和6的“ churchID”。
确切的错误是Error Code: 1054. Unknown column 'new_church' in 'field list'
答案 0 :(得分:0)
经过大量Google搜索,我终于找到了答案。我发现我不需要UPDATE
子句,为了在SET
子句中使用子查询,我需要将子查询嵌套在另一个子查询中。这是我的固定代码:
delimiter $$
CREATE TRIGGER churchID_people_updateTrig BEFORE UPDATE on people
FOR EACH ROW
BEGIN
IF NEW.church != OLD.church THEN
SET new.churchID = (SELECT * FROM (SELECT DISTINCT c.churchID
FROM churches c LEFT OUTER JOIN people p
ON c.name = p.church
WHERE p.church = NEW.church) as x);
END IF;
END
$$
delimiter ;