使用更新触发器删除行

发布于 2024-10-22 04:20:20 字数 380 浏览 2 评论 0原文

我有一个包含两列的表: name(text) 和 count(integer)

如果新名称不存在(count=1),则将其插入表中,否则计数器将递增。我有一个类似的函数,它会减少计数器。我想要实现的是,一旦该计数器达到 0,它就会删除该行。我想到为此使用触发器:

CREATE TRIGGER fooTrigger
AFTER UPDATE OF count ON foo
BEGIN
  DELETE FROM foo WHERE count=0;
END;

问题是,由于某种原因,这样做时触发器似乎会删除每一行。

关于可能出现什么问题的任何提示吗?我怀疑这个问题可能与在桌子本身上使用触发器有关,但我当然不知道..

提前致谢。

I have a table with two columns: name(text) and count(integer)

A new name is inserted in the table if it doesn't exist (with count=1), otherwise the counter is incremented. I have a similar function that instead decrements the counter. What I'd like to achieve is that once this counter reaches 0, it deletes the row. I thought of using a trigger for this:

CREATE TRIGGER fooTrigger
AFTER UPDATE OF count ON foo
BEGIN
  DELETE FROM foo WHERE count=0;
END;

The problem is that for some reason, when doing so the trigger seems to delete every single row.

Any tip about what could be the issue? I'm suspecting the problem could be related to using a trigger on the table itself but I certainly dont' know..

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瑶笙 2024-10-29 04:20:20

一种可能的解决方案是将删除限制为已更新的行。我假设名称列是唯一的(或主键)。以下触发器仅检查已更新行上的计数列:

create trigger fooTrigger
after update of count on foo
for each row when new.count = 0 begin
    delete from foo where name = new.name;
end

EDIT

如果您的名称列不唯一,则可以将删除限制为实际的 rowid(此语法仅限于 sqlit)这意味着,如果您有两行名称为“hello world”并且有两个不同的计数,则删除只会影响首先达到 0 的行!但我仍然认为名称列是唯一的,以实现良好的设计实践:)

create trigger fooTrigger
after update of count on foo
for each row when new.count = 0 begin
    delete from foo where rowid = new.rowid;
end

A possible solution could be limiting the delete to the row that is updated. I assume that the name column is unique (or primary key). The following trigger is only examining the count column on the row that has been updated:

create trigger fooTrigger
after update of count on foo
for each row when new.count = 0 begin
    delete from foo where name = new.name;
end

EDIT

If your name column is not unique, you can limit the delete to the actual rowid (this syntax is limited to sqlit) This means that if you have two rows with the name 'hello world' and two different counts the delete will only affect the row that hits 0 first! But i still assume that the name column is unique, for good design practice :)

create trigger fooTrigger
after update of count on foo
for each row when new.count = 0 begin
    delete from foo where rowid = new.rowid;
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文