如何在MySQL中选择唯一值并按其他字段排序

时间:2013-10-30 13:20:06

标签: mysql sql

我有一个包含以下列和行的数据库

sender      receiver   timestamp
1           176        305
176         1          503
1           116        2011
45          1          106
1           176        309

好。到现在为止还挺好。问题是,我希望一次显示所有数据并按时间戳排序,所以我会得到这样的结果:

sender/receiver      timestamp
116                  2011
176                  503
45                   109

这意味着即使发送者/接收者发生的次数超过一次,我也只能获得最高的时间戳值。

我真的希望你理解我的问题。

2 个答案:

答案 0 :(得分:2)

SELECT  CASE WHEN Sender = 1 THEN Receiver ELSE Sender END `sender/receiver`,
        MAX(timestamp) time_stamp
FROM    tableName
WHERE   1 IN (Sender, Receiver)
GROUP   BY CASE WHEN Sender = 1 THEN Receiver ELSE Sender END
ORDER   BY time_stamp DESC

CASE语句取Receiver的值为Sender = 1,否则为Sender。使用MAX()获取时间戳的最大值。

答案 1 :(得分:0)

另一种选择:

SELECT sender_receiver
     , Max(timestamp) As max_timestamp
FROM   (
        SELECT sender As sender_receiver
             , timestamp
        FROM   your_table
        WHERE  sender <> 1

        UNION ALL

        SELECT receiver As sender_receiver
             , timestamp
        FROM   your_table
        WHERE  receiver <> 1
       ) As x
ORDER
    BY max_timestamp