您正在分组查询中选择非分组字段。不保证返回该组的哪条记录,ORDER BY
处理后处理GROUP BY
。
试试这个:
SELECT m.*
FROM (
SELECT DISTINCT from_userid
FROM who_messages
WHERE to_userid = 41
) md
JOIN who_messages m
ON m.id =
(
SELECT mi.id
FROM who_message mi
WHERE (mi.to_userid, mi.from_userid) = (41, md.from_userid)
ORDER BY
mi.sent DESC, mi.id DESC
LIMIT 1
)
为此创建一个索引以who_message (to_userid, from_userid, sent, id)
使其快速工作。
更新
上述查询将返回来自任何给定用户的最后一条消息的记录(包括其读取状态)。如果您想检查您是否有来自用户的任何未读消息,请使用以下命令:
SELECT m.*, md.all_read
FROM (
SELECT from_userid, MIN(read) AS all_read
FROM who_messages
WHERE to_userid = 41
GROUP BY
from_userid
) md
JOIN who_messages m
ON m.id =
(
SELECT mi.id
FROM who_message mi
WHERE (mi.to_userid, mi.from_userid) = (41, md.from_userid)
ORDER BY
mi.sent DESC, mi.id DESC
LIMIT 1
)
为此,请在who_message (to_userid, from_userid, read)
(除了先前的索引之外)创建一个索引。