使用更新触发器删除行
我有一个包含两列的表: 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种可能的解决方案是将删除限制为已更新的行。我假设名称列是唯一的(或主键)。以下触发器仅检查已更新行上的计数列:
EDIT
如果您的名称列不唯一,则可以将删除限制为实际的 rowid(此语法仅限于 sqlit)这意味着,如果您有两行名称为“hello world”并且有两个不同的计数,则删除只会影响首先达到 0 的行!但我仍然认为名称列是唯一的,以实现良好的设计实践:)
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:
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 :)