我的问题是我正在尝试创建聊天消息系统,
这是我到目前为止所做的。
Chat
chat_id | member_id | added
Member to Chat
member_to_chat_id | member_id | chat_id
Chat Message
chat_message_id | member_to_chat_id | message | added
所以我想得到所有成员参与的聊天。我是这样做的
Select c.chat_id
From member_to_chat m2c
Left Join chat c ON c.chat_id = m2c.chat_id WHERE m2c.member_id = 1
GROUP by c.chat_id
小提琴就在这里 http://sqlfiddle.com/#!9/4d1ab/1
有没有办法让这个群组中的最后一条消息聊天并形成该成员是谁?
预期结果看起来应该是这样的
如果用户Alex处于两个聊天状态,并且他写了最后一条消息
chat_id | member_name | member_message
1 Alex Test1
2 Alex Test2
稍后,如果其他人在与id 1的聊天中添加消息,我们仍会按用户ID 1获取所有聊天记录:Alex但该消息应来自其他成员,所以这样的事情:
chat_id | member_name | member_message
1 John Last Test1
2 Alex Test2
希望现在有意义。
答案 0 :(得分:0)
好的,我希望这是最后一次编辑,我要在这里做的是你怎么做你想要的我一开始并没有完全理解你的问题,但是你最后编辑我的事情就是解决方案:
SELECT * FROM(
SELECT m2c.chat_id, m.name, cm.message
FROM member_to_chat m2c
INNER JOIN chat_message cm
ON m2c.member_to_chat_id = cm.member_to_chat_id
INNER JOIN members m
ON m2c.member_id = m.member_id
WHERE m2c.chat_id IN (SELECT c.chat_id
FROM member_to_chat m2c
INNER JOIN chat c ON c.chat_id = m2c.chat_id
WHERE m2c.member_id = 2)
ORDER BY cm.chat_message_id DESC) resultTable
GROUP BY chat_id
这是小提琴http://sqlfiddle.com/#!9/d7443/9/0来测试它(它是你的小提琴,只是很少编辑以测试查询)GL
修改强>
嗨,我再次提高我的答案。感谢草莓让我为这个问题找到更好的解决方案的提示和建议......(您可以在下面的评论中看到我们的小讨论)...
以下是一切手册的链接,其中所有内容均为https://dev.mysql.com/doc/refman/5.1/en/example-maximum-column-group-row.html
首先是相关子查询的代码:
SELECT m2c.chat_id, m.name, cm.message
FROM member_to_chat m2c
INNER JOIN chat_message cm
ON m2c.member_to_chat_id = cm.member_to_chat_id
INNER JOIN members m
ON m2c.member_id = m.member_id
WHERE m2c.chat_id IN (SELECT c.chat_id
FROM member_to_chat m2c
INNER JOIN chat c ON c.chat_id = m2c.chat_id
WHERE m2c.member_id = 2)
AND cm.chat_message_id = (SELECT MAX(cmm.chat_message_id)
FROM chat_message cmm
INNER JOIN member_to_chat m2cm
on m2cm.member_to_chat_id = cmm.member_to_chat_id
WHERE m2c.chat_id = m2cm.chat_id)
这里结束的是SQL小提琴:http://sqlfiddle.com/#!9/d7443/17/0
这是基于JOIN的第二个解决方案的代码:
SELECT t1.chat_id, name, message FROM (
SELECT m2c.chat_id, m.name, cm.message, cm.chat_message_id
FROM member_to_chat m2c
INNER JOIN chat_message cm
ON m2c.member_to_chat_id = cm.member_to_chat_id
INNER JOIN members m
ON m2c.member_id = m.member_id
WHERE m2c.chat_id IN (SELECT c.chat_id
FROM member_to_chat m2c
INNER JOIN chat c ON c.chat_id = m2c.chat_id
WHERE m2c.member_id = 2)) AS t1
JOIN (SELECT m2c.chat_id, MAX(cm.chat_message_id) as maxChatId
FROM chat_message cm
INNER JOIN member_to_chat m2c
ON m2c.member_to_chat_id = cm.member_to_chat_id
GROUP BY chat_id) AS t2
ON t1.chat_id = t2.chat_id
AND t1.chat_message_id = t2.maxChatId
这是一个小提琴:http://sqlfiddle.com/#!9/d7443/43/0
对于这个答案的改进,这个改进再次得到了很大的贡献,草莓谁给我一个更好的方法来解决这样的问题。再次感谢!
P.S。对不起,我迟到了,我还有其他的想法,但总比没有好。 :) GL