我需要在sql中查询,它可以获取用户所有朋友的最后一条消息的详细信息。我的sql数据库中的字段是:
message_id (primary key)
sender (username of the sender)
message_content (text of the message)
user_id (user id of the app user)
friend_id (user id of the app user's friends)
message_time (time of the message receive on server)
receiver (user id of the receiver)
编辑:到目前为止,我认为我最接近的尝试是
Select * from user_chat_messages where message_id on (Select distinct message_id from user_chat_messages order by message_time limit 1,0);
让我尝试的所有其他查询完全失败:(
答案 0 :(得分:2)
这是一个非常常见的mysql问题,您需要在其自身上加入表以获得具有每个唯一用户的最小值/最大值的结果集。
尝试这样的事情:
SELECT t1.* FROM table t1
JOIN (
SELECT MAX(message_time) AS 'time', friend_id, user_id
FROM table GROUP BY friend_id, user_id
) t2 ON (t1.message_time = t2.time AND t1.friend_id = t2.friend_id AND t1.user_id = t2.user_id)
基本上,您的子查询会查找按friend_id分组的最新时间,然后将其连接回主表,以便它仅从第一个表中提取最新时间的记录。从那里你可以添加一个WHERE语句来只显示来自特定用户的最新消息 - 在子查询中添加条件实际上会提高性能
SELECT t1.* FROM table t1
JOIN (
SELECT MAX(message_time) AS 'time', friend_id, user_id
FROM table
WHERE user_id=? GROUP BY friend_id
) t2 ON (t1.message_time = t2.time AND t1.friend_id = t2.friend_id AND t1.user_id = t2.user_id)