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

Syntax may not be perfect, did not have time to create fiddle. But this has subquery which should get the latest 2 comments related to the post and join that to the post itself. Have to consider that fact that there may be no comments at all hence the test for Is Null from the Left Join.

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

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 に答える