Forum Moderators: coopster

Message Too Old, No Replies

Help needed on Joins

how to join three tables

         

Tourex

7:47 pm on Aug 26, 2005 (gmt 0)

10+ Year Member



Can someone please help me with the SQL syntax to join three tables.

tableA contains a column 'aLocation' which I need to look up in 'bLocation' in tableB.

tableB also has a colum 'bDistrict' that allows me to look up other data in tableC

How can I do a SELECT on tableA joining to tableB and in turn, looking up the correct row in tableC?

There is a possibility of null fields in the 'aLocation' column of tableA

Thanks in anticipation.

coopster

1:59 am on Aug 27, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You join the tables together on their primary keys (or whichever key is necessary to make the relation). A LEFT JOIN will return every row from the left hand table whereas an INNER JOIN would only return rows that matched in all the tables.

Your WHERE clause determines which rows are returned as well.

SELECT  
tableA.aLocation,
tableB.bDistrict,
tableC.*
FROM tableA
LEFT JOIN tableB ON (tableA.aLocation = tableB.bLocation)
LEFT JOIN tableC ON (tableB.bDistrict = tableC.cDistrict)
WHERE tableA.aLocation IS NOT NULL
;

Tourex

7:39 am on Aug 27, 2005 (gmt 0)

10+ Year Member



Thanks Coopster - worked spot on. That's what I thought, but when I tried it I got multiple listings for each record in tableA. Can't think what I was doing - it was the end of a long day.

Anyway, thanks a bunch.