SQL查询问题:X有很多Y.获取所有X并且每X只得到最新的Y.
题
假设我们有两个表。发表评论。邮政有很多评论。假装他们有点填补,以便每个帖子的评论数量不同。我想要一个查询,它会抓住所有帖子,但每个帖子只有最新评论。
我被引导到加入和子查询,但我无法弄明白。
示例输出:
POST1: 评论4(最新的post1)
POST2: 评论2(最新的post2)
Post3: 评论10(最新的post3)
等...
非常感谢任何帮助。感谢。
解决方案
这个答案假定您为每个评论都有一个唯一的标识符,并且它的数字越来越多。也就是说,后来的帖子比早期的帖子更高。不必是顺序的,只需要对应输入顺序。
首先,执行一个提取最大注释ID的查询,按帖子ID分组。
这样的事情:
SELECT MAX(ID) MaxCommentID, PostID
FROM Comments
GROUP BY PostID
这将为您提供帖子ID列表,以及每个帖子ID的最高(最新)评论ID。
然后你加入这个,从那些id中提取评论中的其余数据。
SELECT C1.*, C2.PostID
FROM Comments AS C1
INNER JOIN (
SELECT MAX(ID) MaxCommentID, PostID
FROM Comments
GROUP BY PostID
) AS C2 ON C1.CommentID = C2.MaxCommentID
然后,您加入帖子,以获取有关这些帖子的信息。
SELECT C1.*, P.*
FROM Comments AS C1
INNER JOIN (
SELECT MAX(ID) MaxCommentID, PostID
FROM Comments
GROUP BY PostID
) AS C2 ON C1.CommentID = C2.MaxCommentID
INNER JOIN Posts AS P ON C2.PostID = P.ID
另一种方法根本不使用内部查询的PostID。首先,选择所有唯一帖子的最大评论ID,但不关心哪个帖子,我们知道它们是唯一的。
SELECT MAX(ID) AS MaxCommentID
FROM Comments
GROUP BY PostID
然后执行IN子句,以获取这些注释的其余数据:
SELECT C1.*
FROM Comments
WHERE C1.ID IN (
SELECT MAX(ID) AS MaxCommentID
FROM Comments
GROUP BY PostID
)
然后只需加入帖子:
SELECT C1.*, P.*
FROM Comments AS C1
INNER JOIN Posts AS P ON C1.PostID = P.ID
WHERE C1.ID IN (
SELECT MAX(ID) AS MaxCommentID
FROM Comments
GROUP BY PostID
)
其他提示
从子查询中选择最新评论
e.g
Select *
from Posts po
Inner Join
(
Select CommentThread, CommentDate, CommentBody, Post from comments a
inner join
(select commentthread, max(commentdate)
from comments b
group by commentthread)
on a.commentthread = b.commentthread
and a.commentdate = b.commentdate
) co
on po.Post = co.post
select *
from post
, comments
where post.post_id = comments.post_id
and comments.comments_id = (select max(z.comments_id) from comments z where z.post_id = post.post_id)
如果您仍然遇到旧的mysql版本,那就不知道子查询,您可以使用类似
SELECT p.id, c1.id FROM posts as p LEFT JOIN comments as c1 ON p.id = c1.postId LEFT JOIN comments as c2 ON c1.postId = c2.postId AND c1.id < c2.id WHERE isnull(c2.id) ORDER BY p.id的方法。无论哪种方式,请使用 EXPLAIN 了解性能问题。
不隶属于 StackOverflow