第二次加入的sqlite查询

时间:2015-09-30 18:11:42

标签: sql sqlite select join left-join

我有表格消息:

enter image description here

保留用户对话中的消息

每个对话都是这样的:

enter image description here

现在我有QUERY I

SELECT m.*
FROM 
( SELECT message_conversationId        
  FROM messages as m
  WHERE m.user_id = 1
  GROUP BY message_conversationId
) AS mc
  JOIN 
    messages AS m                          
      ON  m.message_id =        
          ( SELECT mi.message_id            
            FROM messages AS mi
            WHERE mi.message_conversationId     
                  = mc.message_conversationId
            AND mi.user_id = 1
            ORDER BY mi.message_timestamp DESC,  
                     mi.message_id DESC          
            LIMIT 1                              
          )       
  ORDER BY m.message_timestamp DESC
  • ,它会返回每个会话中最后一条消息的列表
  • ** last被定义为last message_timestamp& last message_id

enter image description here

MESSAGES TABLE中的每一个行都包含有关发送消息的一方的信息的信息,例如。我或其他人

当我查询所有对话时我需要知道对话的第二面,所以我需要在此QUERY II中添加一个选择/加入声明

LEFT JOIN 
 (  SELECT message_conversationId, message_from as message_from2, message_avatar_pic_id as message_avatar_pic_id_from2
    FROM Messages  msg_from
        -- not exactly me - but second side selected in prev query !!! --- 
    WHERE message_from <> 'me' COLLATE NOCASE 
    AND user_id == 1
    GROUP BY message_conversationId
  ) not_me ON message_conversationId = not_me.message_conversationId

得到这个结果:

enter image description here

  

如何合并这两个查询I + II?

编辑

  • 我想要离开加入,因为可能没有第二面的对话 - 例如消息只是发送或接收!

0 个答案:

没有答案