聊天应用好友列表

时间:2012-08-07 02:35:32

标签: mysql sql greatest-n-per-group

我有3个MySQL表,即chat_comments,chat_friends和user_details,我想显示一个朋友列表。

我的桌子:

chat_comments(comment_id,comment,user_id,user_id2,date_added)
chat_friends(user_id,user_id2,approved)
user_details(user_id, mainimage_id, fullname)

要执行此操作,我需要一个返回所需字段的查询(u.mainimage_idu.fullnameb.commentb.user_id),以便我可以遍历列表显示一张桌子。

到目前为止

SQL(来自@Andriy M的帮助):

SELECT
cc.comment,
cc.date_added,
u.fullname,
u.mainimage_id 
FROM
user_details u
LEFT JOIN
    chat_comments cc
    INNER JOIN (
        SELECT
            user_id,
            MAX(comment_id) AS maxcomment
        FROM chat_comments WHERE user_id=2020 OR user_id2=2020
        GROUP BY user_id
    ) a ON a.user_id = cc.user_id
       AND a.maxcomment = cc.comment_id
ON a.user_id = u.user_id
WHERE u.user_id IN (
SELECT user_id2
FROM chat_friends
WHERE user_id = 2020
  AND approved = 1
)

上述查询返回登录用户的朋友在对话中发表的最后一条评论,而不是登录用户和他/她的朋友之间的最后评论,无论是谁做的。

我希望它能够单独返回登录用户和他们的朋友之间的最后一条评论,无论是谁创建了它。在chat_messages表中,user_id是发件人,user_id2是接收者。希望它有意义吗?

1 个答案:

答案 0 :(得分:1)

像@imm在评论中所说,你需要使用外部联接。如果是左连接,user_details表应该成为连接的左侧,右侧是chat_commentsa派生表的内部连接的结果。您还需要从user_id IN (…)子选项中删除a条件,然后将其重新应用到user_details表。这里:

SELECT
    cc.comment,
    cc.date_added,
    u.fullname,
    u.mainimage_id 
FROM
    user_details u
    LEFT JOIN
        chat_comments cc
        INNER JOIN (
            SELECT
                user_id,
                MAX(comment_id) AS maxcomment
            FROM chat_comments
            GROUP BY user_id
        ) a ON a.user_id = cc.user_id
           AND a.maxcomment = cc.comment_id
    ON a.user_id = u.user_id
WHERE u.user_id IN (
    SELECT user_id2
    FROM chat_friends
    WHERE user_id = 2020
      AND approved = 1
)
;

或者,您可以使用正确的联接。在这种情况下,您只需移动user_id IN (…)条件,类似于上面的LEFT JOIN解决方案,并将第二个INNER JOIN替换为RIGHT JOIN

SELECT
    cc.comment, cc.date_added, u.fullname, u.mainimage_id 
FROM
    (
        SELECT user_id, MAX(comment_id) AS maxcomment
        FROM chat_comments
        GROUP BY user_id
    ) a
INNER JOIN
    chat_comments cc ON 
        a.user_id = cc.user_id AND
        a.maxcomment = cc.comment_id
RIGHT JOIN
user_details u ON
 a.user_id = u.user_id
WHERE u.user_id IN (select user_id2 from chat_friends where user_id=2020 AND approved=1)