【问题标题】:Is it possible to LIMIT results from a JOIN query?是否可以限制 JOIN 查询的结果?
【发布时间】:2011-01-28 18:46:26
【问题描述】:

我有一个查询当前查询 Post 表,同时 LEFT JOINing Comment 表。它获取所有帖子及其各自的评论。但是,我想限制返回的评论数。我尝试添加一个子选择,但如果我没有将结果限制为 1,则会遇到错误。我真的不确定如何在仍然只使用一个查询的情况下执行此操作。这可能吗?

【问题讨论】:

  • 如果您发布当前查询,您可以获得更好的结果。

标签: mysql join limit


【解决方案1】:

假设您的表格看起来像这样,这应该让您的帖子与每个帖子的三个最近的 cmets:

发帖
id, post_text

评论
id, post_id, comment_text

SELECT id, post_text, comment_text
FROM
(
    SELECT p.id, p.post_text, c.comment_text
           CASE
             WHEN @id != p.id THEN @row_num := 1
             ELSE @row_num := @row_num + 1
           END AS rank,
           @id := p.id
    FROM post p
    LEFT JOIN comment c ON ( c.post_id = p.id )
    JOIN ( SELECT @id:=NULL, @row_num:=0 ) x
    ORDER BY p.id,
             c.id DESC -- newest comments first
) y
WHERE rank <= 3;

子查询用于首先获取最近的 cmets 并为每个帖子编号,而外部选择删除较旧的 cmets。

【讨论】:

    【解决方案2】:

    除非您有一些方便的值可供过滤(例如where pos between 1 and 5),否则您无法限制加入。可以分别选择第一条评论、第二条评论、第三条评论等,并合并结果。像这样丑陋的东西:

    select This, That
    from Post
    left join (
      select Some
      from Comment
      where PostId = Post.Id
      order by CreatedDate
      limit 1,1
    ) x on 1=1
    
    union all
    
    select This, That
    from Post
    inner join (
      select Some
      from Comment
      where PostId = Post.Id
      order by CreatedDate
      limit 2,1
    ) x on 1=1
    
    union all
    
    select This, That
    from Post
    inner join (
      select Some
      from Comment
      where PostId = Post.Id
      order by CreatedDate
      limit 3,1
    ) x on 1=1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-19
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      相关资源
      最近更新 更多