0

I have a mysql select statement as below:-

select user.username, chat.from_user,chat.to_user,chat.message,chat.date_created 
from chat join user on (chat.from_user or chat.to_user) in (user.user_id)
    where(chat.from_user = 3 or chat.to_user = 3) and chat.chat_id IN
(SELECT distinct (MAX(chat.chat_id) )
    FROM chat GROUP BY chat_group_id);

and here is my result

enter image description here

I always get username = admin. My expectation result is username will get correct from / to user.

Please help. Thank you.

2
  • isn't that your result already correct? Commented Feb 22, 2018 at 3:24
  • Hi AKZhang, nope, the result will return username = admin (userid =1). What i want is if the user id = 2, then username will return username from user id = 3 (according to the screenshot - record 1 as attached) Commented Feb 22, 2018 at 3:53

2 Answers 2

1
SELECT 
    IF(chat.from_user=3, to_user
        , IF(chat.to_user=3, form_user, 0)) AS username,
    chat.from_user,chat.to_user,chat.message,chat.date_created 
    FROM chat 
    LEFT JOIN user fr_user ON chat.from_user = user.user_id
    LEFT JOIN user to_user ON chat.to_user = user.user_id -- since you only want to show the TO_USERNAME, you can remove above line
        WHERE (chat.from_user = 3 OR chat.to_user = 3) and chat.chat_id 
    IN
    (SELECT distinct (MAX(chat.chat_id) )
        FROM chat GROUP BY chat_group_id);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi kasnady, thx for your help. your statement is close to what i want. for username, how can i display "opposite" username. Example: if my statement is (chat.from_user = 3 OR chat.to_user = 3), then my username will display username other than 3?
0

I think you intend:

select u.username, c.from_user, c.to_user, chat.message, c.date_created 
from chat c join
     user u
     on u.user_id in (c.from_user, c.to_user) 
where 3 in (c.from_user, c.to_user) and 
      c.chat_id in (select max(c2.chat_id)
                    from chat c2
                    group by chat_group_id
                   );

1 Comment

Hi Gordon, thx for your help. However, i get duplicate records (duplication message column) from your select statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.