从每个对话中获取最后一条消息

时间:2016-08-06 12:26:48

标签: mysql distinct

我有包含id, sender_id, receiver_id, message and conversation_id

的消息的表格

(我通过conversation_id连接他们,他们通过发送第一条消息进行连接,如果有人回复,首先他从他是接收者的消息中搜索conversation_id,并且他回复的人是发送者,并且通过该发送消息具有相同的conversation_id)

现在在消息列表中,我想在每个conversation_id sender_id='$my_id' OR receiver_id='$my_id' DISTINCT输出一个最后一行。SELECT DISTINCT conversation_id, sender_id, message FROM messages WHERE receiver_id='$my_id' ORDER BY id DESC

我正在使用{{1}},但我总是将所有行作为输出:

{{1}}

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT id,conversation_id, sender_id, receiver_id, message FROM message WHERE receiver_id='$my_id' GROUP BY `conversation_id` ORDER BY id DESC LIMIT 1 

答案 1 :(得分:0)

请尝试以下查询:

SELECT 
M.*
FROM messages M
INNER JOIN 
(
    SELECT 
    MAX(id) AS last_id_of_conversation,
    conversation_id
    FROM messages
    GROUP BY conversation_id
) AS t
ON M.id = last_id_of_conversation

<强>解释

SELECT 
 MAX(id) AS last_id_of_conversation,
 conversation_id
FROM messages
GROUP BY conversation_id;

此内部查询将生成一个输出,其中每个conversation_id都会有一行以及对话的最后id值(或最大id)。

稍后在主表(messages)与匹配id上的内部查询返回的结果之间建立内部联接。我希望idprimary key。如果是这样,那么上述查询确保为每个对话带来一行(更具体地说是具有最后一条消息的行)。

修改

SELECT 
M.*
FROM messages M
INNER JOIN 
(
    SELECT 
    MAX(id) AS last_id_of_conversation,
    conversation_id
    FROM messages
    WHERE sender_id = ? OR receiver_id = ?
    GROUP BY conversation_id
) AS t
ON M.id = last_id_of_conversation