我什至不确定标题是否正确,但这是简化的情况。
我有一张表,其中包含邻接列表:
comments
- id (int)
- parent_id (int)
- depth_level (int)
- ...
我想要做的是用 order by 和 limit 查询深度级别 0,对于返回的每一行我想要一个联合查询,该查询返回相同的表和 order by 和 limit 但不同的深度级别,我想要那个子查询只返回与父深度级别相关的行......等等。如果有帮助,我可以限制深度级别。我有点没有参考,像这样:
select * from ( select * from comments where depth = 0 order by id asc LIMIT 10 ) D0
union all
select * from ( select * from comments where depth = 1 order by id asc LIMIT 10 ) D1
我得到联合行,但正如你所看到的,我希望 D1 只包含具有 parent_id 和 D0 id 的行......我希望它用于多个级别。也许这是错误的方法。我知道这是一厢情愿的想法,但如果行数超过提供的限制,如果我能以某种方式获得每一行,那就太好了。
一个例子:
id parent_id depth title
1 0 0 Title 1
2 0 0 Title 2
3 1 1 Title 3
4 1 1 Title 4
5 1 1 Title 5
6 1 1 Title 6
7 1 1 Title 7
8 4 2 Title 8
9 4 2 Title 9
10 4 2 Title 10
11 4 2 Title 11
pseudo:
select * from table where depth = 0 order by id asc limit 1
union
select * from table where depth = 1 and parent_id from firstQuery.id order by id asc limit 2
union
select * from table where depth = 2 and parent_id from secondQuery.id order by id asc limit 3
result:
id parent_id depth title
1 0 0 Title 1
3 1 1 Title 3
4 1 1 Title 4
8 4 2 Title 8
9 4 2 Title 9
10 4 2 Title 10
编辑2:
扩展彼得姆的答案。
(
SELECT *
FROM comments
WHERE depth = 0
ORDER BY id DESC
LIMIT 2
)
UNION ALL
(
SELECT c.*
FROM comments c JOIN
(
SELECT id
FROM comments
WHERE depth = 0
ORDER BY id DESC
LIMIT 2
) p ON c.parent_id = p.id
LIMIT 5
)
id parent_id depth title
1 0 0 Title 1
2 0 0 Title 2
3 1 1 Title 3
4 1 1 Title 4
5 1 1 Title 5
6 1 1 Title 6
7 1 1 Title 7
但我想要的是限制每个父深度级别,而不是限制深度级别的总和。像这样(在这个例子中,每个深度 1 5 个):
id parent_id depth title
1 0 0 Title 1
2 0 0 Title 2
3 1 1 Title 3
4 1 1 Title 4
5 1 1 Title 5
6 1 1 Title 6
7 1 1 Title 7
8 2 1 Title 8
9 2 1 Title 9
10 2 1 Title 10
11 2 1 Title 11
12 2 1 Title 12