我有一个这样的表:
+---------+----------+
| post_id | reply_to |
+---------+----------+
| 1 | 0 |
| 2 | 1 |
| 3 | 2 |
| 4 | 2 |
| 5 | 3 |
| 6 | 5 |
| 7 | 1 |
| 8 | 7 |
| 9 | 8 |
| 10 | 7 |
+---------+----------+
reply_to
只是被回复的帖子的 ID(即 post_id
为 2 是对 post_id
为 1 的回复) .
这是嵌套形式的样子:
1
2
3
5
6
4
7
8
9
10
如何创建执行以下操作的单个查询:
- 查询 1:获取所有回复
post_id = 1
(2 和 7
)的帖子并将结果数限制为 5 - 查询 2:使用从查询 1 中检索到的值,获取子帖子(
3 和 4
,以及8 和10
) 并将结果数量限制为 3 个每个父帖子 - 查询 3:使用从查询 2 中检索到的值,获取子帖子(
5
和9
) 并将结果数量限制为 1 每个父帖子
所以最后,结果应该包括这些 post_ids:2, 3, 5, 4, 7, 8, 9, 10
。
这是我创建的 SQL Fiddle: http://sqlfiddle.com/#!2/23edc/21
请帮忙!
最佳答案
这在 SQL Server 中有效,我认为它是通用 SQL,但我现在无法让 SQL Fiddle 正常工作。
create table test1 (post_id int, reply_to int);
insert into test1 (post_id, reply_to) values
(1,0),(2,1),(3,2),(4,2),(5,3),(6,5),(7,1),(8,7),(9,8),(10,7),
(11,2),(12,2),(13,2),(14,3); /* Added records to test conditions */
/* All replies to post_id=1 */
with q1 as (
select post_id
from test1
where reply_to = 1
)
/* Top 3 replies to all results in q1 */
, q2 as (
select
q1.post_id as parent_post,
t1.post_id as child_post,
count(*) as row_num
from test1 as t1
inner join q1 on t1.reply_to = q1.post_id
left outer join test1 as t2 on t1.reply_to = t2.reply_to
and t1.post_id >= t2.post_id
group by q1.post_id, t1.post_id
having count(*) <= 3
)
/* Get 0 or 1 grandchild posts */
, q3 as (
select
q2.parent_post,
q2.child_post,
t1.post_id as grandchild_post,
count(*) as row_num
from q2
left outer join test1 as t1 on q2.child_post = t1.reply_to
left outer join test1 as t2 on t1.reply_to = t2.reply_to
and t1.post_id >= t2.post_id
group by q2.parent_post, q2.child_post, t1.post_id
having count(*) = 1
)
/* Aggregate the different post ids */
select distinct parent_post as post_id from q3
union
select distinct child_post from q3
union
select distinct grandchild_post from q3
where grandchild_post is not null;
drop table test1;
关于php - 使用先前查询的值获取更多结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27454795/