用于对消息对话进行分组的SQL查询

时间:2011-12-29 03:57:34

标签: sql

我正在尝试根据to_number和from_number以及创建的日期/时间选择2个用户之间的最新记录。

找到记录后,显示消息和时间戳。只要to_number或from_number具有相同的配对,那么这就是我想要显示的消息。

我真的很难找到具有相同数字组合且以前没有列出的记录中来自/来自OR的唯一/来自。

我的数据:

Messages table:
"id","to_number","from_number","message","created_at","dm_user_id"
"1","7325551212","5705551234","new update","2011-12-17T11:26:33-05:00","1"
"2","5705551234","3015551212","next update","2011-12-17T11:26:53-05:00","1"
"3","6095559876","4695551212","trying messages.","2011-12-19T19:20:47-05:00","2"
"4","5705551234","4155551212","did i get this?","2011-12-19T20:04:40-05:00","1"
"5","9075551212","5705551234","Where did this go?","2011-12-19T20:05:51-05:00","1"
"6","9075551212","5705551234","testing","2011-12-19T20:12:53-05:00","1"
"7","3015551212","5705551234","Are you here ","2011-12-19T20:13:34-05:00","1"
"8","6175554567","4695551212","test from app","2011-12-19T22:51:32-05:00","2"

从上面的数据来看,我只想要以下记录,从最新到最旧列出。

注意:并非所有记录都会被返回,因为组合中有/或来自组合。例如,id 2和id 7是相同2个数字之间的消息。只返回最新版本,ID为7.

另一个例子是id 5和id 6 - 它们都来自/来自相同的数字,所以只返回最新的,id 6。:

表示dm_user_id = 1

"3015551212", "Hello",           "2011-12-19T20:13:34-05:00"  # id 7
"9075551212", "testing",         "2011-12-19T20:12:53-05:00"  # id 6
"4155551212", "did i get this?", "2011-12-19T20:04:40-05:00"  # id 4
"7325551212", "new update",      "2011-12-17T11:26:33-05:00"  # id 1

表示dm_user_id = 2

"6175554567", "test from app",    "2011-12-19T22:51:32-05:00"  # id 8
"6095559876", "trying messages.", "2011-12-19T19:20:47-05:00"  # id 3

我尝试了GROUP BY和DISTINCT的不同组合,但没有得到我正在寻找的结果。

select * from messages where dm_user_id = 1
group by to_number, from_number

select * from (
select DISTINCT to_number, from_number dm_user_id
from messages) where dm_user_id = 1

3 个答案:

答案 0 :(得分:1)

使用dm_users表,您需要:

select
    m.*
from
    dm_users u1
    cross join dm_users u2
    inner join messages m on
        u1.phone_number in (m.to_number, m.from_number)
        and u2.phone_number in (m.to_number, m.from_number)
where
    u1.dm_user_id = 1
    and u2.dm_user_id = 2
order by
    m.created_at desc

答案 1 :(得分:0)

这是一个常见问题,基本上您需要来自每个号码的最新消息,TO或FROM,但您不需要重复。您可以在此类greatest-n-per-group

中找到有用的内容

答案 2 :(得分:0)

工作SQL,它只返回给定/来自,来自/到数字对的最近一条消息,并使用最近的第一个进行排序。从this link修改了SQL。

SELECT
   fullMessage.id,
   fullMessage.to_number,
   fullMessage.from_number,
   fullMessage.message,
   fullMessage.dm_user_id
FROM
    messages fullMessage JOIN
    (
        SELECT max(id) as MAX_ID, to_number, from_number
        FROM messages WHERE dm_user_id = 1  # this can be changed for any dm_user_id
        GROUP BY from_number, to_number
    ) maxMessage ON maxMessage.MAX_ID = fullMessage.id
ORDER BY fullMessage.id desc;