我认为您不能在单个查询中完成,但使用recursive_triggers
(SQLite>=3.6.18) 您可以使用固定数量的语句来完成。
检查这个(tt
你的表名在哪里):
-- Schema addition:
PRAGMA recursive_triggers=1;
CREATE TEMP TABLE ancid(id UNIQUE, ancestor);
CREATE TEMP TRIGGER ancid_t AFTER INSERT ON ancid WHEN (SELECT parent FROM tt WHERE id=NEW.ancestor) IS NOT NULL BEGIN
INSERT OR REPLACE INTO ancid SELECT NEW.id, parent FROM tt WHERE id=NEW.ancestor;
END;
-- Getting ancestor from id=3:
INSERT INTO ancid VALUES(3, 3);
SELECT * FROM ancid WHERE id=3;
-- Getting all ancestors:
INSERT OR REPLACE INTO ancid SELECT id, id FROM tt;
SELECT * FROM ancid;