我正在构建一个有点像facebookchat的Chatapplication。我有用户,对话和消息。所有3个都有自己的桌子。现在,我尝试获取包含特定用户的所有会话以及会话的最新消息。
我尝试了这个查询,但事实上我只返回1行,但还有更多行匹配
SELECT conversations.id as converid,
messages.from as messageauthor,
messages.message as message
FROM conversations INNER JOIN (SELECT * FROM messages
ORDER BY date DESC LIMIT 1) as messages
ON messages.conversationid=conversations.id
WHERE user1=3
OR user2=3
当我这样做时
SELECT conversations.id as converid,
messages.from as messageauthor
FROM conversations INNER JOIN messages
ON messages.conversationid=conversations.id
WHERE user1=3
OR user2=3
我得到了所有结果,当然,当我检查converid时,我得到3个唯一的ID,所以至少有3个转换用户ID 3.所以顶部查询也应该返回3.现在我不明白为什么它只返回1行。嵌套查询中的limit 1
是否会影响整个查询?
期待一些指示...
答案 0 :(得分:1)
没有。 limit 1
影响子查询,因此它只返回一行。所以,只有一场比赛。
此查询有什么问题(您的第二个查询,但格式不同):
SELECT c.id as converid, m.from as messageauthor
FROM conversations c INNER JOIN
messages m
ON m.conversationid=c.id
WHERE user1=3 OR user2=3;
我明白了,你想要最新消息。尝试计算并加入:
SELECT c.id as converid, m.from as messageauthor
FROM conversations c INNER JOIN
messages m
ON m.conversationid=c.id join
(select m.conversationid, max(date) as maxdate
from messages m
group by m.conversationid
) mmax
on mmax.conversationid = m.conversationid and m.date = mmax.maxdate
WHERE user1=3 OR user2=3;