2
Table_Users
id  username
1   Jack
2   Marine
3   Katie
4   Hennry

Table_Messages
id  to_id   from_id Messages
1   2   3   Hello
2   3   2   Hi

Need a single query which can return a Message, To Name and From Name

0

2 Answers 2

1

You need to join the table users on table messages twice since you need to get the equivalent names for to andfrom users.

SELECT  a.id,
        b.`username` TO_NAME,
        c.`username`  FROM_NAME,
        a.Messages
FROM    tbl_Messages a
        INNER JOIN users b
            on a.to_ID  = b.id
        INNER JOIN users c
            on a.from_ID = c.id

See SQLFiddle Demo

5
  • Great, i tried it and is working fine but Is this the best way to do it or there can be different syntax also ?
    – Vikki
    Oct 3, 2012 at 12:10
  • so far,I can say that this is the most efficient solution. There are other solutions where in you can get values from the subquery which is less efficient than this. :D
    – John Woo
    Oct 3, 2012 at 12:12
  • 1
    Hi, I see you're new to SO. If you feel an answer solved the problem, please mark it as 'accepted' by clicking the green check mark. This helps keep the focus on older SO which still don't have answers. :D
    – John Woo
    Oct 3, 2012 at 12:14
  • can you explain me how do you decided to use INNER join why not Left/Right Join
    – Vikki
    Oct 4, 2012 at 11:40
  • @Vikki because I assumed that in every record, there is a to_id and from_id. If any of them did not exist, the whole record won't show because INNER JOIN will only display records that returns true on the condition supplied in ON clause.
    – John Woo
    Oct 4, 2012 at 12:20
0

Here is the query :

select messages as Message, (select users from table_users where id=to_id) as "From Name", (select users from table_users where id=from_id) as "To Name" from table_messages;

1
  • wow here is another way which also results the same result as explained above.
    – Vikki
    Oct 3, 2012 at 13:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.