考虑这个树状表结构:
CREATE TABLE nodes(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  parent INTEGER,
  descendant_count INTEGER NOT NULL DEFAULT 0,
  FOREIGN KEY(parent) REFERENCES nodes(id) ON DELETE CASCADE
);
该descendant_count列存储后代记录的数量。
现在我正在手动维护它,通过增加每个新插入的值(或在删除时减少它)。本质上我一直在获取父记录,然后运行
 UPDATE nodes SET descendant_count = (descendant_count + 1) ? WHERE...
在每个父母身上,直到我到达根源。显然,这在深度嵌套的结构上相当慢。
是否可以使用触发器来实现这一点?或者有没有更快、更可靠的方法呢?
更新 - 11.08.03
SQLite 似乎支持递归触发器。因此,如果我只更新单个节点的计数,那么触发器应该能够更新所有父节点的计数:
CREATE TRIGGER setCounts AFTER UPDATE ON nodes
WHEN (NEW.descendant_count <> OLD.descendant_count)
BEGIN
  -- subtract old counts
  UPDATE nodes
    SET descendant_count = descendant_count - OLD.descendant_count
    WHERE id = NEW.parent;
  -- add new counts
  UPDATE nodes
    SET descendant_count = descendant_count + NEW.descendant_count
    WHERE id = NEW.parent;
END;
我测试了它,似乎数字是正确的,所以这到底是可能的吗?