2017-06-21 177 views
-1

我只想INSERT觸發器後創建插入在歷史表中的新行。爲什麼在運行查詢時出現錯誤?無法創建觸發器

訂單

create table orders 
(
    id int auto_increment 
     primary key, 
    id_user int not null, 
    picture_name varchar(100) not null, 
    time date not null, 
    constraint FK_USER 
     foreign key (id_user) references stef.users (id) 
) 
; 

create index FK_USER_idx 
    on orders (id_user) 
; 

歷史

create table history 
(
    id int auto_increment 
     primary key, 
    id_order int not null, 
    id_action int not null, 
    time date not null, 
    constraint FK_ORDER 
     foreign key (id_order) references stef.orders (id), 
    constraint FK_ACTION 
     foreign key (id_action) references stef.actions (id) 
) 
; 

create index FK_ORDER_idx 
    on history (id_order) 
; 

create index FK_ACTION_idx 
    on history (id_action) 
; 

下了扳機......

CREATE TRIGGER orders_AFTER_INSERT 
AFTER INSERT ON stef.orders 
FOR EACH ROW 
    BEGIN 
    INSERT INTO history('id_order', 'id_action', 'time') 
    VALUES (NEW.id, 1, NOW()); 
    END; 

我只是想創建AFTE r插入觸發器以在歷史記錄表格中插入新行。爲什麼在運行查詢時出現錯誤?

+1

你得到什麼錯誤? –

回答

1

試試這個

DELIMITER $$ 
CREATE TRIGGER orders_AFTER_INSERT 
AFTER INSERT ON stef.orders 
FOR EACH ROW 
BEGIN 
    INSERT INTO history(`id_order`, `id_action`, `time`) 
    VALUES (NEW.id, 1, NOW()); 
END$$ 
DELIMITER ; 

你需要暫時覆蓋分隔符因此MySQL可以聲明的觸發(或過程,或功能)和身體的末端的體內端之間進行區分。

編輯:單引號(')僅使用過表示字符串值,字段名用`(或在某些配置的"

+0

日誌:[2017-06-21 19:45:09] [42000] [1064]你的SQL語法錯誤;檢查對應於你的MySQL服務器版本使用「」附近id_order」,‘id_action’,‘時間’) [2017年6月21日19時45分09秒] VALUES(NEW.id,1正確的語法手冊,NOW()); [2017年6月21日19時45分09秒] END」第5行 – Kryshtop

+0

我沒有符號‘id_action「之前,爲什麼會出現‘’id_action’ – Kryshtop

+0

哦,那些是錯的分隔符,以及! – Uueerdo

0
CREATE TRIGGER orders_AFTER_INSERT 
AFTER INSERT ON stef.orders 
FOR EACH ROW 
BEGIN 
    INSERT INTO stef.history() 
    VALUES (null, NEW.id, 1, NOW()); 
END