我有3张桌子:
发布,评论和评论。
这是一种多对多的关系。
我想为每个帖子选择最后一条评论。 所以类似(通过create_at DESC限制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
它对于一对多关系非常有效,但我不能为多对多关系搭便车。
注意:我重命名了我的桌子。在我的代码中,我不使用评论和发布。我确实需要多对多的关系。
谢谢你
答案 0 :(得分: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
答案 1 :(得分: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