Mysql - 按另一个语句的计数顺序

时间:2013-11-06 16:25:04

标签: mysql sql

我正在尝试通过来自朋友的未读消息计数来订购当前用户的朋友列表。朋友对当前用户有更多未读消息,他应该被放在列表中。

我设法将一个查询放在一起,该查询返回特定用户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

1 个答案:

答案 0 :(得分:1)

这可以满足您的需求吗?

我刚接受了你的第二个查询,嵌套它并添加了一个带有messages表和相应分组的左连接。

我相信它可以更有效地构建(没有额外的嵌套)但是我有点担心它会如何与你在那里的GROUP_CONCAT一起表现(加上我不确定单词表的作用),并且那里表中没有足够的数据来测试它。

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