【问题标题】:Getting more results using value from previous query使用先前查询的值获取更多结果
【发布时间】:2015-02-11 19:44:22
【问题描述】:

我有一张这样的桌子:

+---------+----------+
| 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 of 2 是对 post_id of 1 的回复)。

这是嵌套形式时的样子:

1
    2
        3
            5
                6
        4
    7
        8
            9
        10

我怎样才能创建一个单个查询来执行以下操作:

  • 查询 1: 获取所有回复 post_id = 1 (2 and 7) 的帖子,并将结果数限制为 5 个
  • 查询 2: 使用从 查询 1 检索到的值,获取子帖子(3 and 48 and 10)并将结果数限制为 3 每个父帖子
  • 查询 3:使用从 查询 2 检索到的值,获取子帖子(59)并将结果数限制为 1 个父帖

所以最后,结果应该包括这些 post_ids:2, 3, 5, 4, 7, 8, 9, 10

这是我创建的 SQL Fiddle:http://sqlfiddle.com/#!2/23edc/21

请帮忙!

【问题讨论】:

  • 单个查询的用途是什么?似乎它只会增加不必要的复杂性。
  • 看起来您可以使用单个 SP(存储过程)来解决您的需求。
  • 您确定不喜欢stackoverflow.com/a/27454902/4350148 的答案吗?它完成了这项工作。再看一眼并发表评论。

标签: php mysql sql mysqli


【解决方案1】:

这适用于 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2021-02-18
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多