我有一张这样的表:
+---------+----------+
| 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是对1 {1}的回复。
这是嵌入表单时的样子:
post_id
如何创建执行以下操作的单个查询:
1
2
3
5
6
4
7
8
9
10
(post_id = 1
)的所有帖子,并将结果数量限制为5 2 and 7
和3 and 4
)并限制数量每个帖子的结果为3 8 and 10
和5
)并限制每个帖子的结果为 所以最后,结果应该包含这些post_id:9
。
以下是我创建的SQL小提琴: http://sqlfiddle.com/#!2/23edc/21
请帮忙!
答案 0 :(得分:0)
这适用于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;