所以我有两张表chats
和chats_reply
。结构如下。
聊天
--------------------------------------------------
| chat_id | user_one | user_two | created_at
--------------------------------------------------
| 1 | 1 | 2 | something here
--------------------------------------------------
chats_reply
-------------------------------------------------------------------------
| chatReply_id | chat_id | user_id | reply | created_at
-------------------------------------------------------------------------
| 1 | 1 | 1 | Message 1 | something here
-------------------------------------------------------------------------
| 2 | 1 | 2 | Message 2 | something here
-------------------------------------------------------------------------
我的查询有点问题。让我们说我的user_id是1.我想返回所有聊天列表,其中包含最后发送的消息。我已经有了列出所有聊天记录的查询,但它没有返回最后一条消息,它返回了对话的第一条消息。这是我的问题:
SELECT
chats.chat_id,
chats.created_at AS ChatTime,
chats_reply.reply,
chats_reply.created_at AS ReplyTime,
chats_reply.status,
users.name,
users.last_name,
users.email
FROM chats
INNER JOIN chats_reply
ON chats.chat_id = chats_reply.chat_id
INNER JOIN users
ON users.user_id =
CASE
WHEN chats.user_one = '1'
THEN chats.user_two
WHEN chats.user_two = '1'
THEN chats.user_one
END
WHERE chats.user_one = '1' OR chats.user_two = '1'
GROUP BY chats_reply.chat_id
ORDER BY chats_reply.chatReply_id DESC
此查询返回我期望的所有内容,问题是当我希望它返回Message 1
时,它会从chats_reply
表返回Message 2
。非常感谢任何帮助。
答案 0 :(得分:2)
使用https://www.datacamp.com/courses/financial-trading-in-r
进行过滤。不是WHERE
:
GROUP BY