2017-06-21 143 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