I have below query running on my users and chats table to join and I’m trying to group by on my chats table for user_id OR receiver_id not just user_id like you can see below in SQL query inside INNER JOIN.
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
I tried GROUP BY user_id OR receiver_id but I can’t seem to get information for id 286 for either receiver_id or user_id.
Is there a way we can achieve it and group by so that we can look into both columns and come up with results from both?
Do I need to do two queries and join them together instead?
If you are looking for most recent chat record, why don’t you just sort the results by created and get the first row like this: