简体   繁体   English

如何使用两个连接获取最后的数据

[英]How to get last data using two join

I have one chat table there is reference id of user table use in user_from and user_to. 我有一个聊天表,在user_from和user_to中有用户表使用的引用ID。 Now I have to a query for get a chat member list from chat table like facebook caht list. 现在我需要查询从facebook caht list这样的聊天表中获取聊天成员列表。 with whom I have chat and I have to find name of user from user table and unread counter 我和谁聊天,我必须从用户表和未读计数器中找到用户名 在此输入图像描述

Please give me solution for this Thanks 请给我解决方案谢谢

I think your subquery needs to be correlated, which will be slow. 我认为你的子查询需要相关,这将是缓慢的。

Use JOIN instead. 请改用JOIN。

SELECT 
    users.id AS userid,
    chat_box.id AS msgid,
    first_name,
    last_name,
    profile_pic,
    LEFT(message, 50) AS message,
    u.unreadcounter
FROM
    chat_box
        LEFT JOIN
    users ON (chat_box.user_from = users.id)
        LEFT JOIN
    (SELECT 
        u.id, COUNT(c.id) unreadcounter
    FROM
        chat_box c
    JOIN users u ON (c.user_from = u.id)
    WHERE
        c.read = 0 && c.user_to = 45
    GROUP BY u.id) u ON users.id = u.id
WHERE
    (user_from = 45 OR user_to = 45)
        && users.id != 45
GROUP BY users.id 
UNION SELECT 
    users.id AS userid,
    chat.id AS msgid,
    first_name,
    last_name,
    profile_pic,
    LEFT(message, 50) AS message,
    0 AS unreadcounter
FROM
    chat_box AS chat
        LEFT JOIN
    users ON (chat.user_to = users.id)
WHERE
    (user_from = 45 OR user_to = 45)
        && users.id != 45
GROUP BY users.id
ORDER BY msgid DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM