1

私は3つのテーブルを持っています:

投稿、投稿コメント、コメント。

これは多対多の関係です。

投稿ごとに最後のコメントを選択したい。したがって、(select * from comment order by create_at DESC limit 1) のようなものはここでは機能しません。

そして、私は次のようなものが欲しい:

select *
  from post as p
    left join post_comment as pc on (pc.post_id = p.id)
    left joint comment as c on (c.id = pc.comment_id)
    left joint comment as c2 on (c2.id = pc.comment_id and c2.id > c.id)
  where c2.id is null

1対多の関係では非常にうまく機能しますが、多対多ではうまくいきません。

注: テーブルの名前を変更しました。私のコードでは、コメントと投稿を使用しません。そして、多対多の関係が必要です。

ありがとうございます

4

2 に答える 2

0

私はそのようなことをしました:

select *
  from post as p
    left join post_comment as pc on (pc.post_id = p.id)
    left join comment as c on (c.id = pc.comment_id)
    left outer join
            (post_comment as pc2
                inner join comment as c2 on (c2.id = pc2.comment_id)
            ) on (bc2.post_id = p.id and c1.created_at < c2.created_at)
  where c2.id is null
于 2013-02-04T11:00:37.193 に答える