选择每个对话的第一行

时间:2018-08-05 07:19:15

标签: mysql sql

我如何选择特定用户to_id = 1在每个对话的第一行。

最大的问题是,当交换的第一条消息没有top_id = 1时,最终列出了第二条具有from_id = 1且不应该的消息。

这是SQLFIDDLE的链接: http://www.sqlfiddle.com/#!9/7a772b/4

在SQLFIDDLE中,列出Test 1Test 4时应仅列出Test 1,因为对话Test 4Test 3开始拥有to_id = 1

SQL

SELECT t1.*, m2.message, m2.from_id FROM
    (SELECT to_id,message, MIN(created_at) AS created_at FROM messages m
    WHERE to_id = 1
    GROUP BY to_id,message) AS t1
INNER JOIN messages m2 ON t1.created_at = m2.created_at

2 个答案:

答案 0 :(得分:0)

您可以使用min功能和子查询

select t1.*,m2.mensagem,m2.remetente_id  from
    (select destinatario_id ,min(created_at) as created_at from mensagens m
    where destinatario_id=1
    group by destinatario_id) as t1
inner join mensagens m2 t1.created_at =m2.created_at 

答案 1 :(得分:0)

您可以使用以下方式最早进行对话:

select least(remetente_id, destinatario_id) as id1,
       greatest(remetente_id, destinatario_id) as id2,
       min(id) as min_id
from mensagens m
where 1 in (remetente_id, destinatario_id)
group by id1, id2;

(这假设id随着日期时间升序,这是合理的。)

然后您可以使用joinin获取完整的行:

select m.*
from mensagens m join
     (select least(remetente_id, destinatario_id) as id1,
             greatest(remetente_id, destinatario_id) as id2,
             min(id) as min_id
      from mensagens m1 
      where 1 in (remetente_id, destinatario_id)
      group by id1, id2
     ) mm
     on mm.min_id = m.id;