我在我的users
和chats
表上运行以下查询以加入,我正在group by
表{for} chats
上user_id OR receiver_id
只需user_id
,就像您在INNER JOIN
内的SQL查询中看到的那样。
SELECT c.*, users.username, users.firstname, users.lastname
FROM chats c
INNER JOIN( SELECT MAX(created) AS Date, user_id, receiver_id, chat, type, id
FROM chats
WHERE receiver_id = 286 OR user_id = 286
GROUP BY user_id ) cc ON cc.Date = c.created AND cc.user_id = c.user_id
LEFT JOIN users ON users.id = c.user_id
WHERE c.receiver_id = 286 OR c.user_id = 286
我尝试了GROUP BY user_id OR receiver_id
,但我似乎无法获取有关receiver_id或user_id的id 286的信息。
我们有没有办法实现它并分组,以便我们可以查看两个列并从中得出结果?
我是否需要进行两次查询并将它们连接在一起?
答案 0 :(得分:1)
如果您正在寻找最新的聊天记录,为什么不按创建的方式对结果进行排序,并获得第一行:
SELECT c.*, users.username, users.firstname, users.lastname
FROM chats c, users u
WHERE (c.receiver_id = 286 OR c.user_id = 286) AND
u.id = c.user_id
ORDER BY created DESC
LIMIT 1