我有一个聊天表,在user_from和user_to中有用户表使用的引用ID。 现在我需要查询从facebook caht list这样的聊天表中获取聊天成员列表。 我和谁聊天,我必须从用户表和未读计数器中找到用户名
请给我解决方案 感谢
答案 0 :(得分:0)
我认为您的子查询需要相关,这将很慢。
改为使用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