0

我正在构建一个有点像 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影响整个查询?

期待一些指点...

4

1 回答 1

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;
于 2013-06-24T15:58:46.313 回答