我正在尝试通过来自朋友的未读消息计数来排序当前用户的朋友列表。朋友对当前用户的未读消息越多,他应该放在列表中的位置越高。
我设法整理了一个查询,该查询返回来自特定用户 ID 的当前用户的未读消息计数。
SELECT COUNT(*) AS unread_msg
FROM messages m LEFT JOIN users u ON m.from_user_id = u.id
WHERE 1 /* Current user, unread msg to */ IN (from_user_id,to_user_id)
AND 2 /* Friend, unread msg from */ IN (from_user_id,to_user_id)
AND to_user_id = 1 /* Current user, unread msg to */
AND seen = 0
在 SO-sql 大师的帮助下,我查询了好友列表:
SELECT a.name_surname,
a.avatar,
GROUP_CONCAT(DISTINCT w.word ORDER BY w.word ASC) AS friend_words,
(a.friend_id) AS friend_msg_id /* Unread msg from id */
FROM (
SELECT f1.asked_user_id AS friend_id,
f1.created,
u.name_surname,
u.avatar
FROM friends AS f1
INNER JOIN friends AS f2 ON f1.asked_user_id = f2.asker_user_id
INNER JOIN users AS u ON f1.asked_user_id = u.id
AND f1.asker_user_id = f2.asked_user_id
WHERE f1.status = 1 AND f2.status = 1
AND f1.asker_user_id = 1 /* Current user id */
) a
LEFT JOIN connections c ON c.user_id = a.friend_id
LEFT JOIN words_en w ON c.word_id = w.id
GROUP BY 1
任何想法如何统一这些查询?所以我在第二个查询中得到 unread_msg ?