4

我试图限制每个帖子只有 2 条评论,
我在帖子表中选择,我想为每个帖子获得 2 条评论

架构:


帖子表

------------------------------------
  id   |   content   |    date     |
  25    |   hello     |  20/10/2013 |

评论表

------------------------------------------------
  id   |   content   |    post   |    date     |
  1    |   hello     |    25     |  20/10/2013 |

朋友们能不能帮帮我,我很困惑!
感谢之前,任何帮助将不胜感激。

4

3 回答 3

1

MySQL supports the LIMIT keyword, which allows you to control how many rows are returned; ideal when displaying data over many pages. You can use LIMIT in your sql query like this

在你的情况下

select * from posts p join comments c on p.id=c.post and
      c.id> (select id from comments  where post=p.id order by id DESC LIMIT 2,1)
于 2013-11-11T11:52:35.150 回答
1

语法可能不完美,没来得及创造小提琴。但这有子查询,它应该获取与帖子相关的最新 2 条评论并将其加入帖子本身。必须考虑这样一个事实,即可能根本没有评论,因此从左连接中对 Is Null 进行测试。

Select *
From Posts p
Left Outer Join Comments c
On c.post = p.id
Where 
    (        c.id Is Null
        Or    c.id In
        (
            Select c2.id
            From Comments c2
            Where c2.post = p.id
            Order by c2.id Desc
            Limit 2
        )
    )
于 2013-11-11T12:06:20.653 回答
1

此查询返回每个帖子的最后 2 条评论:

SQLFiddle 演示

select p.content post_content,
       c.content comment_content

from posts p
left join comments c on 
    (p.id=c.post)
    and 
    c.id>
    (select id from comments  
        where post=p.id
        order by id DESC LIMIT 2,1)
于 2013-11-11T12:13:54.583 回答