我想在A列中选择最大值。现在,我在A列中有多个最大值。如何使用最大值取1行并去除其余部分?我尝试使用distinct
和limit 1
但没有成功。
预期:只有2行,1有消息“srth”,另一行有“the-same-ts-1”或“the-same-ts-2”但不是两者都有,因为他们有相同的最大值1413588888
我的查询:
SELECT A.*, DU.user as username, DU.thumbnail
FROM DB_CHATS A
INNER JOIN (
SELECT distinct max(timestamp) TS, user, partner
FROM db_chats
GROUP BY user,partner ) T
on A.TimeStamp=T.TS
and A.user=T.User
LEFT JOIN db_users DU on t.partner = DU.id
where A.user = 'utQ8YDxD6kSrlI5QtFOUAE4h'
小提琴:sqlfiddle
答案 0 :(得分:1)
如果您不关心哪个行返回了最长时间戳,则可以在查询结尾添加group by user, partner, timestamp
。
SELECT A.*, DU.user as username, DU.thumbnail
FROM DB_CHATS A
INNER JOIN (
SELECT distinct max(timestamp) TS, user, partner
FROM db_chats
GROUP BY user,partner ) T
on A.TimeStamp=T.TS
and A.user=T.User
LEFT JOIN db_users DU on t.partner = DU.id
where A.user = 'utQ8YDxD6kSrlI5QtFOUAE4h'
group by user, partner, timestamp