插入后触发到INCREMENT的增加

时间:2019-03-28 17:43:39

标签: mysql triggers sql-update sql-insert

我正在尝试创建一个触发器,如果​​一行的faction.factionname与INSERT的cards.faction相匹配,则在将INSERT插入卡后增加派生表中的卡数。

到目前为止,我已经尝试了几种不同的方法,但是下面的代码是我最接近的猜测

create table cards(
    cardid int not null,
    faction varchar(255) not null,
    primary key(cardid)
);

create table faction(
    factionname varchar(255) not null,
    cardcount int not null,
    primary key(factionname)
);


create trigger updatecountinsert
    after insert on cards
    for each row
begin
    update faction
    set cardcount=carcount+1
    where last_insert_id().faction=faction.factionname
end; 

基本上,如果我插入的值(11,'x')x是一个派系,如果一行的派系具有factionname = x 触发应该 该行的“卡数”增加1

1 个答案:

答案 0 :(得分:0)

DELIMITER $$

CREATE TRIGGER updatecountinsert
AFTER INSERT ON cards
FOR EACH ROW
BEGIN
   -- NEW is used to qualify references values of the row that was just inserted
   -- e.g. NEW.faction is a reference to the value in the faction column
   UPDATE faction f
      SET f.cardcount = f.cardcount + 1
    WHERE f.factionname = NEW.faction ;
END;
$$

DELIMITER ;