选择每个会话的第一行

bhmjp9jg  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(309)

如何选择特定用户的每个会话的第一行 to_id = 1 .
最大的问题是当交换的第一条消息没有 top_id = 1 最后列出下一个 from_id = 1 而且不应该。
这是指向SQLFIDLE的链接:http://www.sqlfiddle.com/#!9月7日A772B/4
在sqlfiddle中列出 Test 1 以及 Test 4 什么时候上市 Test 1 ,因为谈话 Test 4 开始于 Test 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
dsekswqp

dsekswqp1#

你可以用 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
k3fezbri

k3fezbri2#

您可以使用以下方法获得对话的最早时间:

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 是随日期时间上升的,这是合理的。)
然后可以使用 join 或者 in :

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;

相关问题