簡體   English   中英

mySQL - 為每個帖子選擇2條最新評論

[英]mySQL - Select 2 latest comments for each posts

我試圖限制每個帖子只有2條評論,
我在郵政表中選擇,我希望每個都有2條評論

架構:


帖子表

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

評論表

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

你能幫我朋友嗎,我很困惑!
在此之前,任何幫助將不勝感激。

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)

語法可能不完美,沒有時間創建小提琴。 但這有子查詢,應該得到與帖子相關的最新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條評論:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM