简体   繁体   中英

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. Now I have to a query for get a chat member list from chat table like 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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