多个最大值时仅选择1行

时间:2014-10-17 21:28:32

标签: mysql sql

我想在A列中选择最大值。现在,我在A列中有多个最大值。如何使用最大值取1行并去除其余部分?我尝试使用distinctlimit 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

1 个答案:

答案 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

http://sqlfiddle.com/#!2/efe6e/2