1

我有 3 个表消息,消息用户和用户。

我想提取用户在每个会话中收到最后一条消息的会话列表,并且我也想访问该消息的数据。对话列表的顺序应该是包含最先收到的最后一条消息的顺序。(对话只是 message.conversation 上的一个 id)

我得到的东西几乎像这样工作:

SELECT mu.*
     , m.id message_id
     , m.conversation message_conversation
     , m.from message_from
     , m.text message_text
     , m.date_created message_date_created
     , user1.type user1_type
     , user1.name user1_name
     , user1.email user1_email
     , user1.avatar_blob_key user1_avatar_blob_key 
  FROM message_user mu
  LEFT 
  JOIN message m
    ON m.id = mu.message 
  LEFT 
  JOIN user user1 
    ON user1.id = m.from 
 WHERE mu.to = THE_USER_ID 
 GROUP  
    BY m.conversation 
 ORDER 
    BY mu.message DESC;

但是这个查询没有收到最后一条消息,而是每个对话中的第一条消息:/

看起来这部分ORDER BY message_user.message DESC没有被查询使用。

4

2 回答 2

3
SELECT mu.*
     , message.id message_id
     , message.conversation message_conversation
     , message.from message_from
     , message.text message_text
     , message.date_created message_date_created
     , user1.type user1_type
     , user1.name user1_name
     , user1.email user1_email
     , user1.avatar_blob_key user1_avatar_blob_key 
  FROM message_user mu
  LEFT 
  JOIN (select max(id) id,`from`
       from message
       group by `from`)max
    ON max.id = mu.message 
  LEFT 
  JOIN user user1 
    ON user1.id = message.from 
 WHERE mu.to = THE_USER_ID 
 GROUP  
    BY message.conversation 
 ORDER 
    BY mu.message DESC;
于 2013-10-29T15:11:09.657 回答
2

So, to reiterate your request, the message rows that should be returned should be ones where the last message in the given conversation is one to the user in question. Assuming that is correct, you could try something like the following:

Select MU.*
     , M.id As message_id
     , M.conversation As message_conversation
     , M.from As message_from
     , M.text As message_text
     , M.date_created As message_date_created
     , FromUser.type As user1_type
     , FromUser.name As user1_name
     , FromUser.email As user1_email
     , FromUser.avatar_blob_key As user1_avatar_blob_key 
From message_user As MU
    Left Join message As M
        On M.id = MU.message
            And M.date_created =    (
                                    Select Max( M1.date_created )
                                    From message As M1
                                    Where M1.conversation = M.conversation
                                    )
    Left Join user As FromUser
        On FromUser.id = M.from
Where MU.to = <some user id>
Group By M.conversation
Order By MU.message Desc;
于 2013-10-29T15:10:41.013 回答