SQL 查询父子节点并限制行数的写法?

2021-01-27 14:54:25 +08:00
 Kaciras

数据库里有一张 tree 表保存了树结构的数据,有 idparent 两列,子节点的 parent 等于父节点的 id,没有父节点的 parent=0

能否做到在一次查询中获取:

比如:

INSERT INTO "tree" ("id", "parent") VALUES (1, 0);
INSERT INTO "tree" ("id", "parent") VALUES (2, 1);
INSERT INTO "tree" ("id", "parent") VALUES (3, 1);
INSERT INTO "tree" ("id", "parent") VALUES (4, 1);
INSERT INTO "tree" ("id", "parent") VALUES (5, 0);
INSERT INTO "tree" ("id", "parent") VALUES (6, 5);
INSERT INTO "tree" ("id", "parent") VALUES (7, 5);
INSERT INTO "tree" ("id", "parent") VALUES (8, 5);
INSERT INTO "tree" ("id", "parent") VALUES (9, 5);
INSERT INTO "tree" ("id", "parent") VALUES (10, 0);

查询出结果应该是(顺序无所谓):

+-----+--------+
| id  | parent |
+-----+--------+
|  1  |   0    |
|  5  |   0    |
|  2  |   1    |
|  3  |   1    |
|  6  |   5    |
|  7  |   5    |
+-----+--------+

尝试写了下但是不对,数据库是 pg 和 mariadb,不知道如何限制每个节点的前两个。

WITH top AS (SELECT * FROM tree WHERE parent=0 LIMIT 2)
(SELECT * FROM top)
UNION
SELECT B.* FROM top 
JOIN (SELECT * FROM tree LIMIT 2) AS B
ON B.parent=top.id
774 次点击
所在节点    问与答
1 条回复
tianhei826
2021-01-27 15:18:30 +08:00
with tmp as
(select id
from a
where parent = 0
and rownum <= 2
order by parent asc)
select a.*
from tmp t, a a
where t.id = a.parent
and rownum <= 2
order by parent desc;

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/748916

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX