trigger mysql unknown table

强颜欢笑 提交于 2021-02-17 06:34:25

问题


I've been trying to solve this problem. Here is the code:

CREATE TRIGGER some_trigger AFTER UPDATE ON table_a
    FOR EACH ROW BEGIN
    DECLARE tname VARCHAR(20);
     IF (table_a.field_offer=1) THEN
      SET tname='table_b';
    ELSEIF (table_a.field_offer=0) THEN
      SET tname='table_c'; 
    END IF;   
      IF ((new.field_state = 0)) THEN
       UPDATE tname join table_a on tname.ID=table_a.ref_field
       SET tname.STOCK = tname.STOCK -1;
      ELSEIF ((new.field_state = 1)) THEN
       UPDATE tname join table_a on tname.ID=table_a.ref_field
       SET tname.STOCK = tname.STOCK +1;
      END IF;  
    END;

I am getting:

Unknown table 'table_a' in field list. Field_offer and field_state can be null.


回答1:


I've shown below what was said in the comments to the question:

CREATE TRIGGER some_trigger AFTER UPDATE ON table_a
    FOR EACH ROW BEGIN
    DECLARE tname VARCHAR(20);
    IF (NEW.field_offer=1) THEN
       UPDATE `table_b` 
       SET STOCK = CASE NEW.field_state 
                   WHEN 0 THEN STOCK - 1 
                   WHEN 1 THEN STOCK + 1 
                   ELSE STOCK 
                   END
       WHERE ID=NEW.ref_field
       ;
    ELSEIF (NEW.field_offer=0) THEN
       UPDATE `table_c` 
       SET STOCK = CASE NEW.field_state 
                   WHEN 0 THEN STOCK - 1 
                   WHEN 1 THEN STOCK + 1 
                   ELSE STOCK 
                   END
       WHERE ID=NEW.ref_field
       ;
    END IF;
    ...

Note that I changed the updates from UPDATE ... JOIN as MySQL does not allow you to change the data of the triggered table; while you were not actually updating table_a, the JOIN could have been enough for MySQL to have objected... that and the joins would've updated every row in table_b/c that had a match in table_a, not just table_a rows related to the values in or row of the trigger.



来源:https://stackoverflow.com/questions/38576794/trigger-mysql-unknown-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!