我这里有2张桌子。
Posts Comments
post_id comment_id
content post_id
create_datetime
content
我必须编写一个SQL查询,它返回每个帖子(按内容按字母顺序排序)及其最后一条评论。
它只返回1行(我有多个帖子),行中返回的评论不是最新的。
我写过这个sql查询: -
SELECT posts.content AS post,
Max(Unix_timestamp(comments.create_datetime)),
comments.content AS comment
FROM posts,
comments
WHERE posts.post_id = comments.post_id
但是,这并没有做必要的事情。我做错了什么?
答案 0 :(得分:0)
您需要先获取最大日期,然后获取评论。
SELECT post_id, MAX(create_datetime) as max_date
FROM Comments
GROUP BY post_id
取
SELECT C.post_id, C.content
FROM Comments C
JOIN (SELECT post_id, MAX(create_datetime) as max_date
FROM Comments
GROUP BY post_id
) T
ON C.create_datetime = T.max_date
注意:如果可以联系,你必须小心
答案 1 :(得分:0)
SELECT posts.content AS post,
t.create_datetime ,
t.content AS comment
FROM posts
Inner Join (
select comments.content , comments.post_id , comments.create_datetime
from comments
where ( comments.create_datetime, comments.comment_id ) in
(select max(comments.create_datetime ), max(comments.comment_id)
from comments
group by comments.post_id ) ) t on t.post_id = posts.post_id;
答案 2 :(得分:-1)
尝试通过减少冗余来利用关系。在您的数据库结构中,您的Comments
表当前拥有足够的数据来完全忽略Posts
表。这也会造成异常。
请考虑两个表格中posts_id
和content
的含义。您希望公共字段与表相关联,但您不希望将整个表内容放入另一个表中以使其可关联。