views:

41

answers:

1

I have the following table, let's call it People:

id     | customer | shipper | buyer |
1      | 1        | 2       | 3     |
2      | 4        | 5       | 6     |
3      | 7        | 8       | 9     |

And this ties in to a User_ID table:

id     | Name  |
1      | Stan  |
2      | Brian |
3      | Amy   |

What's the best practice for returning the table such as People only instead of id's replacing that with actual values? I realize I could do this with subqueries... but I think there's a better way.

+3  A: 

Use joins - here's a good link explaining them visually:

   SELECT c.name AS customer,
          s.name AS shipper,
          b.name AS buyer
     FROM PEOPLE p
LEFT JOIN USER c ON c.id = p.customer
LEFT JOIN USER s ON s.id = p.shipper
LEFT JOIN USER b ON b.id = p.buyer
OMG Ponies
In most databases subqueries or joins will do the same thing in this instance. The optimiser will come up with the same query plan either way..
Mongus Pong
That isn't something you should rely on - correlated subqueries in the SELECT clause have been known to execute once for every row. While they work on small datasets, the approach does not scale as the data set increases.
OMG Ponies
Don't you want 'shipper' and 'buyer' in the latter two ON clauses?
peejaybee
@peejaybee: Corrected, thx for catching the copy/paste error
OMG Ponies
@OMG Ponies, Id be surprised if the optimiser didnt work it out for a query as simple as this (I dont think its the size of the dataset that matters - more likely the complexity of the subquery), but you are right - that is something that will bite you (hard!) if you don't watch out for it!
Mongus Pong