Jump to content

[SOLVED] Join a table more than once from a single table?


iamgregg

Recommended Posts

I'm fine with normal join queries, but I'm having trouble with this one. I don't think I explained it well in the topic title so I'll go into more detail.

Two tables:
users
pairs

Table users has details about said users.
The pairs table contains the 2 fields: user_1 and user_2, which are the respective users IDs.

In one qury I want to grab the name of each user. I can do it fine for one of them but not sure how to both, e.g. how would I expand this?

SELECT pairs.user_1, users.name
FROM pairs, users
WHERE pairs.user_1 = users.id

I can't figure out how to do it for both? The furthest I get is

SELECT pairs.user_1, pairs.user_2, users.name
FROM pairs, users
WHERE pairs.user_1 = users.id AND pairs.user_2 = users.id

I know it's wrong.

Anyone know?

Thanks.
Link to comment
Share on other sites

You can achive this by adding the table `users` in the FROM section twice but using a different  alias each time

e.g.


SELECT pairs.user_1, users_1.name, pairs.user_2, users_2.name
FROM pairs, users AS users_1,users AS users_2
WHERE  pairs.user_1 = users_1.id AND pairs.user_2 = users_2.id


Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.