【问题标题】:Search the last comment in a many-to-many relation在多对多关系中搜索最后一条评论
【发布时间】:2013-02-04 10:25:30
【问题描述】:

我有 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

它对于一对多关系非常有效,但对于多对多,我无法驾驭它。

注意:我重命名了我的表。在我的代码中,我不使用评论和帖子。而且我确实需要多对多关系。

谢谢你

【问题讨论】:

  • 您使用的是哪个 DBMS?甲骨文? Postgres?
  • 如果您使用 ORM,那么可能用哪个 ORM 和哪种语言标记您的问题。也许你会得到你需要的确切答案。
  • 好的,我会标记它 Doctrine2

标签: sql doctrine-orm many-to-many max


【解决方案1】:

您查询的主表应该是 postcomment,您可以按 postid 分组并获取 max(postcomment),假设它是一个 autoincrementid。

然后您只需将结果与其他表连接起来即可获取其余数据。 由于您可能需要来自其他表的大量数据,并且为了避免将所有这些数据添加到分组依据,我会使用 CTE:

(CTE 是一种 sql server 语法,如果您不使用 sql server,则必须使用另一种机制来存储此临时数据)

with my_cte as
(
    select idpost, max(idcomment)  as last_comment_id
    from postcomment pc 
    group by idpost
)
select *
from my_cte 
     join post p on p.idpost=my_cte.idpost
     join comment c on c.idcomment=my_cte.last_comment_id

【讨论】:

  • 我使用一个 orm。所以我更喜欢with 声明。不过谢谢。
【解决方案2】:

我做了类似的事情:

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

【讨论】:

    猜你喜欢
    • 2012-01-24
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2013-09-30
    • 2015-10-29
    • 2019-05-10
    • 1970-01-01
    相关资源
    最近更新 更多