创建更新后触发器后如何解决错误1054

时间:2019-05-20 16:28:30

标签: mysql sql

创建触发器后更新数据时出现问题。触发器连接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';

人员表具有以下字段:

  • PersonID int NOT NULL PK
  • 名字varchar NOT NULL
  • 姓氏varchar NOT NULL
  • 电话varchar
  • 列表项
  • 教会varchar NOT NULL
  • churchID int NOT NULL fk(引用教堂表中的churchID)
  • 地址varchar
  • 通过电子邮件发送varchar
  • 注意varchar

教堂数据库是

  • churchID INT NOT NULL pk
  • 名称varchar NOT NULL pk
  • 电话VARCHAR
  • 地址VARCHAR
  • 注释VARCHAR

我要使用此触发器进行的操作是,每当更改个人教堂时,它都会自动将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'

1 个答案:

答案 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 ;