タイトルが正しいかどうかさえわかりませんが、単純化した状況を次に示します。
隣接リストを含むテーブルが1つあります。
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 には、D0 id を持つparent_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