SQL触发器:如果给定值在第一个表

时间:2015-05-09 19:06:44

标签: mysql sql database triggers sql-insert

正如标题所说,我试图在一个表中插入一行,在另一个表上插入后触发,但前提是第一个表中已经存在给定值。

示例:

我有一个表国家,它存储了国家/地区及其ID:

国家

id   country 
1    England 
2    France  
...  ...    

我还有另一个表事件,它存储有关事件的信息,如下所示:

事件

id  timestamp   city    country
1   13435636    London  England
2   45635742    Paris   France
... ... ... ...

我想要做的事情:创建一个触发器,以便在事件表上插入后,在国家/地区表格中插入一个新行,其中包含该事件所在的国家/地区发生在,但仅限于该国家/地区表中尚未存在该国家/地区。

我尝试过:

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    INSERT INTO countries (country) VALUES (New.country)
    WHERE NOT EXISTS (SELECT country FROM countries WHERE country = New.country)

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    IF NOT EXISTS (SELECT country FROM countries WHERE country = New.country)
    BEGIN
        INSERT INTO countries (country) VALUES (New.country)
    END

CREATE TRIGGER Update
AFTER INSERT ON events FOR EACH ROW
    IF NOT EXISTS (SELECT country FROM countries WHERE country = New.country)
        INSERT INTO countries (country) VALUES (New.country)

除了一些其他变体之外,我得到的只是语法错误(错误#1064)。

1 个答案:

答案 0 :(得分:0)

试试这个

    CREATE TRIGGER Update
    AFTER INSERT ON events FOR EACH ROW
    BEGIN
        INSERT INTO countries (country) VALUES (New.country)
        WHERE New.country NOT IN (SELECT country FROM countries)
   END