【问题标题】:Select top 1 for distinct value according to time根据时间选择前 1 个不同的值
【发布时间】:2014-03-22 11:53:41
【问题描述】:

我有以下表格:

tblMyFriends

ID     FriendID     GroupID      Public
1        F1                       YES
2        F2                       YES
3        F3                       NO
3                     G1          YES
4                     G2          YES
6        F4                       NO
7        F5                       YES
8                     G3          NO

tblMessages

ID     FriendID     GroupID      MyMessage     MyTime
1        F1                        A1            2 
2        F4                        A2            3
3        F1                        A3            1
3                     G2           Y1            1
4                     G2           Y2            3 
6        F3                        A4            3
7        F3                        A5            4
8                     G3           Y3            5
9        F4                        A6            5
10       F4                        A7            6

我需要获取最新消息(仅前 1 条),即时间降序。 另外,后面是我列表中剩余的朋友或群组列表

因此,我需要查询,它将返回以下输出:

tbl输出

ID     FriendID     GroupID      MyMessage     MyTime
    1        F4                        A7            6 
    2                     G3           Y3            5
    3        F3                        A5            4
    4                     G2           Y2            3
    5        F1                        A1            2
    6        F2                                      0
    7        F5                                      0    
    8                     G2                         0

我正在使用 SQLite

【问题讨论】:

  • 朋友,你试过了吗?

标签: ios sql database sqlite


【解决方案1】:

要获取没有消息的朋友/群组的记录,请使用outer join

要获得一个更容易加入的密钥,请使用coalesce function。 (这要求空字段为 NULL。)

要为每组记录获取一个结果记录,请使用 GROUP BY:

SELECT tblMyFriends.FriendID,
       tblMyFriends.GroupID,
       tblMessages.MyMessage,
       MAX(tblMessages.MyTime)
FROM tblMyFriends
LEFT JOIN tblMessages
       ON COALESCE(tblMyFriends.FriendID, tblMyFriends.GroupID) =
          COALESCE(tblMessages.FriendID,  tblMessages.GroupID)
GROUP BY tblMyFriends.FriendID,
         tblMyFriends.GroupID

这需要 SQLite 3.7.11 或更高版本;否则,MyMessage 值将不会来自与 MAX 匹配的同一记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多