Rajnikanth
Rajnikanth

Reputation: 2785

MySQL combine two table fields by matching their id

For example I have created two tables.

Table One: t5zgu_property_message

msg_from msg_to subject message

57       42     xxxxx   xxxxxx
57       42     xxxxx   xxxxxx
57       42     xxxxx   xxxxxx
42       42     xxxxx   xxxxxx

Table Two: t5zgu_users

id username

42 Jack
57 Rocky

I want output like this way:

msg_from msg_to subject message msg_from  msg_to

57       42     xxxxx   xxxxxx  Rocky     Jack
57       42     xxxxx   xxxxxx  Rocky     Jack
57       42     xxxxx   xxxxxx  Rocky     Jack
42       42     xxxxx   xxxxxx  Jack      Jack

My current query is:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from
FROM 
    t5zgu_property_message,
        t5zgu_users
WHERE
    t5zgu_property_message.msg_from = t5zgu_users.id

ORDER BY t5zgu_property_message.id DESC

This query is working perfect with msg_from and getting right output but I don't know how to write for msg_to.

Any ideas or suggestions? Thanks.

Upvotes: 0

Views: 141

Answers (2)

Conrad Lotz
Conrad Lotz

Reputation: 8828

Try the following statement:

SELECT 
        p.id,
        p.msg_from,
        p.msg_to,
        p.subject,
        p.message,
        u1.username as msg_from
        u2.username as msg_to
FROM 
    t5zgu_property_message p LEFT JOIN 
        t5zgu_users u1 ON u1.id = p.msg_from
    LEFT JOIN t5zgu_users u2 ON u2.id = p.msg_to

ORDER BY p.id DESC

Upvotes: 0

Aleks G
Aleks G

Reputation: 57316

All you need is to join the users table again:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from,
        t5zgu_users2.username as msg_to
FROM 
    t5zgu_property_message,
    t5zgu_users,
    t5zgu_users t5zgu_users2
WHERE
    t5zgu_property_message.msg_from = t5zgu_users.id
    AND
    t5zgu_property_message.msg_to = t5zgu_users2.id

ORDER BY t5zgu_property_message.id DESC

Or the same thing using JOIN syntax:

SELECT 
    t5zgu_property_message.id,
        t5zgu_property_message.msg_from,
        t5zgu_property_message.msg_to,
        t5zgu_property_message.subject,
        t5zgu_property_message.message,
        t5zgu_users.username as msg_from,
        t5zgu_users2.username as msg_to
FROM 
    t5zgu_property_message
    JOIN t5zgu_users ON t5zgu_property_message.msg_from = t5zgu_users.id
    JOIN t5zgu_users t5zgu_users2 ON t5zgu_property_message.msg_to = t5zgu_users2.id
ORDER BY t5zgu_property_message.id DESC

Upvotes: 5

Related Questions