是否可以从JOIN查询中获取LIMIT结果?

时间:2010-03-17 21:01:20

标签: mysql join limit

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

2 个答案:

答案 0 :(得分:2)

假设您的表格看起来像这样,那么每个帖子的帖子应该包含最近的三条评论:

发表
idpost_text

<强>注释
idpost_idcomment_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;

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

答案 1 :(得分:1)

除非您有一些方便的值可以过滤(例如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