表 chat_history 記錄聊天歷史:
id:自增主鍵from_uid:發送方 UIDto_uid:接收方 UID需求:獲取某用戶(如 uid='xxx')的**最新聯系人列表**,按最後消息時間倒序,支援分頁。
SELECT MAX(id) AS mid, from_uid, to_uid
FROM chat_history
WHERE from_uid='xxx' OR to_uid='xxx'
GROUP BY from_uid, to_uid
ORDER BY mid DESC
缺陷:雙向通信產生兩行(A→B 與 B→A),需程序層合併,無法直接 LIMIT 分頁。
核心思路:將 (from_uid, to_uid) 無序對轉換為有序唯一標識。
SELECT
MAX(id) AS mid,
from_uid,
to_uid,
CASE to_uid
WHEN 'xxx' THEN CONCAT(to_uid, from_uid)
ELSE CONCAT(from_uid, to_uid)
END AS to_from_uid
FROM chat_history
WHERE to_uid = 'xxx' OR from_uid = 'xxx'
GROUP BY to_from_uid
ORDER BY mid DESC
LIMIT 0, 20
to_from_uid(from_uid, to_uid) 聯合索引優化 WHERE 條件同類場景: