我试图限制每个帖子只有2条评论,我在帖子表中选择,我希望每个评论都有2条评论
------------------------------------
id | content | date |
25 | hello | 20/10/2013 |
评论表
------------------------------------------------
id | content | post | date |
1 | hello | 25 | 20/10/2013 |
你可以帮我朋友吗,我很困惑!
在此之前,感谢任何帮助。
答案 0 :(得分: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)
答案 1 :(得分: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
)
)
答案 2 :(得分:1)
此查询返回每篇帖子的最后2条评论:
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)