4

我有一个包含几十万个条目的表,我正在尝试使用查询来获取特定接收者 ID 的结果集,并按发送者 ID 对它们进行分组。我当前的 SQL 查询有效,但我想知道在语句中使用两个 MAX 调用是否存在任何潜在问题。它看起来像这样:

SELECT MAX(id) as id, sender_id, receiver_id, MAX(date) as date
FROM     messages
WHERE    receiver_id=5 and belong_to=5
GROUP BY sender_id

表日期如下所示:

id sender_id receiver_id content date                 belong_to           
-- --------- ----------- ------- -------------------  ---------
1  5         7           test    2013-03-11 10:33:54  7
2  5         7           test    2013-03-11 10:33:54  5
3  13        7           test 2  2013-03-13 12:01:36  7
4  13        7           test 2  2013-03-13 12:01:36  13
5  5         7           test 3  2013-03-14 09:15:37  7
6  5         7           test 3  2013-03-14 09:15:37  5
7  25        5           data1   2013-03-15 11:01:36  5
8  25        5           data1   2013-03-15 11:01:36  25
9  16        5           data2   2013-03-17 09:17:17  5
10 16        5           data2   2013-03-17 09:17:17  16
11 25        5           data3   2013-04-05 09:17:17  5
12 25        5           data3   2013-04-05 09:17:17  16

我的查询的输出是这样的:

id sender_id receiver_id date               
-- --------- ----------- -------------------
9  16        5           2013-03-17 09:17:17
11 25        5           2013-04-05 09:17:17

使用 MAX 调用此查询是否有任何问题?如果是这样,还有什么选择?

4

2 回答 2

3

我不太了解您的结构(因此,例如,此示例假定可以对 UNIQUE 施加一个键sender_id, receiver_id, date, belong_to),但我怀疑您想要这样的东西。根据需要按用户过滤..

SELECT x.* 
  FROM messages x
  JOIN 
     ( SELECT sender_id
            , receiver_id
            , MAX(date) max_date 
         FROM messages 
        GROUP 
           BY receiver_id
            , sender_id
     ) y 
    ON y.sender_id = x.sender_id 
   AND y.receiver_id = x.receiver_id 
   AND y.max_date = x.date
 WHERE x.belong_to = x.receiver_id;
于 2013-05-11T13:50:46.803 回答
0

根据评论,您想要的是:

' 唯一的 [特定接收者 ID 的发送者 ID 列表以及每个 [接收者] 的最新条目(日期)'

如果您指的是具有该单个接收者的最新进入日期的所有发件人,那么:

Select * From Messages m
Where date = (Select Max(date) From messages
              Where receiver_id = m.receiver_id) 
    And receiver_id = 5 -- add this if you only want results for one receiver_id

如果 otoh,您的意思是“特定接收者 ID 的唯一发送者 ID 列表以及每个 [接收者-发送者组合] 的最新条目(日期)”,然后执行此操作

Select * From Messages m
Where date = (Select Max(date) From messages
              Where Sender_id = m.Sender_id 
                  And receiver_id = m.receiver_id) 
    And receiver_id = 5 -- add this if you only want results for one receiver_id
于 2013-05-11T13:35:41.497 回答