SQLite In Clause 在触发器中不起作用

SQLite In Clause not working in trigger

i have two tables Table1 and Table2. Table1 have columns ID,stringIDs and Table2 Columns ID,data

i have created a trigger to delete rows based on table1. it doesn't works if comma Seperated stringIDs are more than one. it works if stringIDs is only single value

create trigger tgTriggerName after delete
on Table1
begin
delete from Table2 where ID in (old.stringIDs);
end

Gordon 是对的,这个 table 结构 确实 可能不是你想要的。但是如果出于某种原因你必须这样做,这个查询可能会完成你想要的:

delete from Table2 
where ID = old.stringIDs                   -- ID matches exactly
  or old.stringIDs like ID + ',%'          -- Or ID is at beginning of list
  or old.stringIDs like '%,' + ID          -- Or ID is at end of list
  or old.stringIDs like '%,' + ID + ',%'   -- Or ID is in middle of list

但那是一团糟。不要这样做。而是从 Table1 中删除 stringIDs 列,并向 Table2 添加一个名为 Table1ID 的列以指示此 Table2 记录属于哪个 Table1 ID。所以 Table2 看起来像这样

ID     Table1ID     Data
1      1            some data
2      1            some data
3      2            some data
4      2            some data
5      2            some data
...

那么您的触发查询可以简单地是:

delete from Table2
where Table1ID = old.ID

更干净的方法是完全跳过触发器并使用级联删除执行外键约束。但我觉得这是另一天的教训。

'stringIDs' from table1 使用外键引用将它们保存在另一个 table 中,而不是在新的 table 上应用触发器以从 table 中删除记录 2