开发者

MYSQL trigger see if record exists first?

So I have a trigger that works on update. Totally works fine.

Insert in cars(date, id, parent_id) values (date, ford, 2)

What I need to do is to actually check to see if the parent_id already exists. If it does do开发者_JAVA技巧 nothing but if it does not exist then do the insert statement.

right now i have

SET @myVar1 = (SELECT parent_id from cars where parent_id = NEW.id);
IF @myVar1 = NULL;
Insert in cars(date, id, parent_id) values (date, ford, 2);
ENDIF;

I keep getting sysntax error. How am I writing this worng?


The problem is on this line:

Insert in cars(date, id, parent_id) values (date, ford, 2);

The in should be INTO. That's the syntax error.

That said, you might be better served with an INSERT...ON DUPLICATE KEY or REPLACE INTO statement rather than an on-update trigger. Be careful with REPLACE INTO though, as it can be dangerous (but the danger can be somewhat mitigated by using transactions).


dunno if this what you really need. but you can try this one

SET @myVar1 = (SELECT parent_id from cars where parent_id = NEW.id);
IF (@myVar1 is NULL) then
Insert into cars(`date`, id, parent_id) values (date(), new.`name`, new.id);
END IF;

or

Insert into cars(`date`, id, parent_id) values (date(), new.`name`, new.id) on duplicate key update `date`=date();

on mysql must be "end if" not "endif".

new.name is assumes that id field on car from trigger table

you can use on duplicate key update if cars table use primary key or unique key like mention above

and if you doesn't want to change any record if exists then after key update change to id=id or you can use any field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜