我不認爲你可以在單個查詢做到這一點,但recursive_triggers
(SQLite的> = 3.6.18),你可以用它做固定數量的報表。
檢查這個(其中tt
是你的表名):?在sqlite3的基本遞歸查詢]
-- 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;
的可能重複(http://stackoverflow.com/questions/7456957/basic-recursive-query -on-sqlite3) –
@Anna K.我添加了更新 –