考虑下表,其中包含有关目录结构的信息:
CREATE TABLE t (id INTEGER, name TEXT, parent INTEGER);
INSERT into t VALUES
(1, "", 1),
(2, "a", 1),
(3, "b", 2),
(4, "c", 3),
(5, "d", 1);
SELECT * FROM t;
从该表中可以获得包含路径名称
的列""
"a"
"a/b"
"a/b/c"
"d"
似乎某种递归是必要的。到目前为止,我只设法创建父目录的文本列:
SELECT b.id, b.name name, b.parent parent, a.name as parent_name
FROM t a INNER JOIN t b ON a.id = b.parent;
如何从这里开始?
答案 0 :(得分:1)
是的,您必须使用递归,在SQLite中可以使用WITH
来完成:
WITH RECURSIVE tf AS (
SELECT id, name, parent, name AS full, parent AS p FROM t
UNION
SELECT id, name, parent,
(SELECT name FROM t WHERE id=tf.p) || "\" || full,
(SELECT parent FROM t WHERE id=tf.p)
FROM tf WHERE p IS NOT NULL
)
SELECT id, name, full FROM tf WHERE p IS NULL;