创建TRIGGER给出错误(MySQL)

时间:2014-10-26 18:04:27

标签: php mysql sql database phpmyadmin

我试图在我的mysql数据库中创建一个触发器但是我一直收到错误。这是我的查询:

CREATE TRIGGER update_counters AFTER INSERT ON cheats_main FOR EACH ROW
BEGIN
    DELETE FROM meta_info;
    INSERT INTO meta_info (system_id, system, game_count, cheat_count) VALUES (
        SELECT id, system,
        (SELECT count(g1.id) FROM cheats_games g1 WHERE g1.system = s.id) AS games_counter,
        (SELECT count(c2.id) FROM cheats_main c2 JOIN cheats_games g2 ON g2.id = c2.game_id
        WHERE g2.system = s.id) AS cheats_counter 
        FROM systeme AS s
    );
END;

MySQL表" meta_info"有这种结构:

system_id | system | game_count | cheat_count | created

我不断得到的错误是:

  

MySQL说:文档1064 - 你有   SQL语法中的错误;查看与您的手册相对应的手册   MySQL服务器版本,用于在''附近使用正确的语法在第3行

第3行是:

DELETE FROM meta_info;

当我删除此行时,我收到此错误:

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法   靠近' SELECT id,system,           (SELECT count(g1.id)FROM cheats_games g1 WHERE g1.system' at line 4

在这种情况下,第4行是:

SELECT id, system (...)

内部SELECT工作得很好。我得到一个包含这些列的结果表:

id | system | games_counter | cheats_counter

感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:3)

您需要定义另一个分隔符,而不是;。否则,DB将在第一个;处停止触发器定义,这将是不完整的

delimiter |
CREATE TRIGGER update_counters AFTER INSERT ON cheats_main FOR EACH ROW
BEGIN
    DELETE FROM meta_info;
    INSERT INTO meta_info (system_id, system, game_count, cheat_count)
        SELECT id, system,
        (SELECT count(g1.id) FROM cheats_games g1 WHERE g1.system = s.id) AS games_counter,
        (SELECT count(c2.id) FROM cheats_main c2 JOIN cheats_games g2 ON g2.id = c2.game_id
        WHERE g2.system = s.id) AS cheats_counter 
        FROM systeme AS s;
END
|
delimiter ;

如果你在insert语句中使用select,那么就像这样使用它

insert into t1(col1, col2)
select a, b from t2