选择mysql中每个会话的最后一个会话消息

时间:2014-03-28 08:09:27

标签: mysql sql

我的疑问:

SELECT *
  FROM messages_status mst
       INNER JOIN messages msg 
             ON mst.msg_id=msg.id
 WHERE mst.user_id = 1 
       AND mst.status NOT IN (0,3)
ORDER BY 
       msg.created_at DESC

将显示在此sqlfiddle中: http://sqlfiddle.com/#!2/be010/1/0

你有2个表:messages和message_status 首先包含内容,sender_id,创建时间和会话ID等消息数据。 第二个具有特定的用户消息状态,是读取还是删除。

我想收到每个对话的最后一条消息

任何想法?

4 个答案:

答案 0 :(得分:1)

这是小提琴。 http://sqlfiddle.com/#!2/be010/116

这是您可以使用的查询:

SELECT *
FROM 
(SELECT messages.id as id, 
messages.conv_id as conv_id,
max(messages.created_at) as created_at FROM messages,messages_status
WHERE messages.id = messages_status.msg_id
AND messages_status.user_id = 1 
AND messages_status.status NOT IN (0,3)
GROUP BY messages.conv_id) max_created
INNER JOIN messages 
ON messages.created_at = max_created.created_at
INNER JOIN  messages_status mst 
ON mst.msg_id=max_created.id
GROUP BY messages.conv_id
ORDER BY max_created.created_at DESC;

答案 1 :(得分:1)

检查出来:

SELECT *
  FROM messages_status mst
       INNER JOIN (SELECT messages.* FROM messages INNER JOIN (
                    SELECT sender_ID,conv_id,MAX(created_at) as maxtime FROM messages
                    GROUP BY sender_ID,conv_id) as t1 ON
                    t1.sender_id = messages.sender_id AND t1.conv_id = messages.conv_id AND 
                    t1.maxtime = messages.created_at) msg 
                    ON mst.msg_id=msg.id
WHERE mst.user_id = 1 AND mst.status NOT IN (0,3)
ORDER BY msg.created_at DESC

这是link

答案 2 :(得分:1)

当你问获取每个对话的最后一条消息时 你可以试试这个

select *
from messages msg
inner join
(
  select max(created_at) created_at
  from messages
  group by conv_id
) m2
  on msg.created_at = m2.created_at

Inner JOIN messages_status mst ON msg.id=mst.msg_id 
WHERE mst.user_id = 1 AND mst.status NOT IN (0,3)

http://sqlfiddle.com/#!2/be010/89

答案 3 :(得分:1)

<强> SQLFIDDLEExample

查询:

SELECT msg.*
FROM messages_status mst
INNER JOIN messages msg ON mst.msg_id=msg.id
LEFT JOIN messages ms2
 ON ms2.conv_id = msg.conv_id
 AND ms2.created_at > msg.created_at
WHERE mst.user_id = 1 
 AND mst.status NOT IN (0,3)
 AND ms2.created_at is null

结果:

| ID | SENDER_ID | CONV_ID |       CONTENT |                   CREATED_AT |                   UPDATED_AT |
|----|-----------|---------|---------------|------------------------------|------------------------------|
| 16 |         3 |       3 |         hy :) | March, 26 2014 16:38:17+0000 | March, 26 2014 16:38:17+0000 |
| 14 |         1 |       1 | kjhkjhkjh  kl | March, 26 2014 16:16:25+0000 | March, 26 2014 16:16:25+0000 |