【问题标题】:TRIGGER to INCREMENT after INSERT插入后触发增量
【发布时间】:2019-03-28 17:43:38
【问题描述】:

如果行的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; 

基本上如果我插入 values(11,'x') x 是派系如果一行派系有 factionname=x 触发器应该 将该行的“cardcount”增加 1

【问题讨论】:

  • 这种方法有什么问题?你的实际问题是什么?请具体
  • "where last_insert_id().faction=faction.factionname " 行声称存在语法错误。我正在尝试使代码末尾的触发器起作用。也感谢您的编辑
  • 你确实有一个似乎是carcount 而不是cardcount - 修复它有帮助吗?
  • 哦,我的错。我修复了它,但我仍然遇到同样的错误。
  • 您通常在触发器中使用 OLD 和 NEW;不是 last_insertid()。 ...即使需要 last_insert_id(),it does not return a row you could use to reference fields like that,并且依赖于您的表缺少的自动递增 id。

标签: mysql triggers sql-update sql-insert


【解决方案1】:
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 ;

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 2011-12-06
    • 2012-03-30
    • 2013-12-06
    • 2011-08-24
    • 2012-11-12
    相关资源
    最近更新 更多