我有以下查询:
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
我得到了评论的最后日期,但是没有得到最后的评论(根据那个日期),我得到了第一个评论。那个怎么样?
答案 0 :(得分:1)
尝试这种方式:
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
)
答案 1 :(得分:1)
假设您使用的是Sql-Server:由于没有分组,您的查询不应该正常工作。
我认为您需要的是在订购后TOP(1)
<{em> 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
答案 2 :(得分:1)
这正是您的查询所要求的:您正在选择名称,最大评论日期,然后是第一个加入的评论(在这种情况下,恰好是第一个评论)。你需要在那里加入额外的逻辑来获得最新的评论。
不同的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
字段作为其主键。