我有以下查询:
SELECT f.name, MAX( cmt.created_at ) AS CommentDate, cmt.comment AS LastComment
FROM families f
LEFT JOIN comments cmt ON f.id = cmt.commentable_id
WHERE f.id =12212
我得到了评论的最后日期,但我没有得到最后的评论(根据那个日期),而是得到了第一个评论。那个怎么样?
这正是您的查询所要求的:您正在选择名称、最长评论日期,然后是加入的第一个评论(在这种情况下,恰好是第一个评论)。您需要在其中添加额外的逻辑才能获得最新评论。
不同的 SQL 风格有不同的方法来做到这一点,但以下应该适用于任何地方:
select f.name,
cmt.created_at as CommentDate,
cmt.comment as LastComment
from families f
left join comments cmt
on cmt.commentable_id = f.id
left join comments latest_cmt
on latest_cmt.commentable_id = f.id
and latest_cmt.created_at > cmt.created_at
where f.id = 12212
and latest_cmt.id is null;
我们假设评论表有一个id
字段作为它的主键。
试试这个方法:
SELECT f.name, cmt.created_at AS CommentDate, cmt.comment AS LastComment
FROM families f
LEFT JOIN comments cmt ON f.id = cmt.commentable_id
WHERE f.id =12212
and cmt.created_at = (
SELECT MAX( cmt.created_at )
FROM families f
LEFT JOIN comments cmt ON f.id = cmt.commentable_id
WHERE f.id =12212
)
或者
SELECT f.name, cmt.created_at AS CommentDate, cmt.comment AS LastComment
FROM families f
LEFT JOIN comments cmt ON f.id = cmt.commentable_id
WHERE f.id =12212
and cmt.created_at = (
SELECT MAX( created_at )
FROM comments
WHERE commentable_id =12212
)
假设您在 Sql-Server 上:您的查询不应该工作,因为没有分组。
我认为您需要的是TOP(1)
订购后 cmt.created_at DESC
;
SELECT TOP (1) f.name, cmt.created_at AS CommentDate, cmt.comment AS LastComment
FROM families f
LEFT JOIN comments cmt ON f.id = cmt.commentable_id
WHERE f.id =12212
ORDER BY cmt.created_at DESC
对于 mysql,我认为您可以LIMIT
改用TOP
:
SELECT f.name, cmt.created_at AS CommentDate, cmt.comment AS LastComment
FROM families f
LEFT JOIN comments cmt ON f.id = cmt.commentable_id
WHERE f.id =12212
ORDER BY cmt.created_at DESC
LIMIT 1