0

我正在尝试通过来自朋友的未读消息计数来排序当前用户的朋友列表。朋友对当前用户的未读消息越多,他应该放在列表中的位置越高。

我设法整理了一个查询,该查询返回来自特定用户 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 ?

和小提琴:http ://www.sqlfiddle.com/#!2/129a6/1

4

1 回答 1

1

这能满足您的需要吗?

我刚刚接受了您的第二个查询,将其嵌套并添加了带有消息表和适当分组的左连接。

我相信它可以更有效地构建(没有额外的嵌套),但我有点担心它会如何与你有的 GROUP_CONCAT 一起执行(另外我不确定 words 表的作用),而且还不够表中的数据来测试它。

select b.name_surname,b.avatar,b.friend_words,b.friend_msg_id, count(m.id) from (
    SELECT a.name_surname as name_surname,
           a.avatar as 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
) b
left join messages m on m.to_user_id = 1 
          and m.from_user_id = b.friend_msg_id 
          and m.seen = 0
group by b.name_surname,b.avatar,b.friend_words,b.friend_msg_id
于 2013-11-06T17:29:58.840 回答