SQL question, multiple JOINS in one query
Posted: Tue Nov 08, 2005 9:13 am
I have the following (simplyfied) database structure:
Person
persnr
name
workarea
PersonExt
persnr
email
Workareas
code
region
unit
location
Locations
id
Address
Street
City
The bold text is the database name with the fieldnames under it. The Person table contains information about different persons. Person.persnr refers to PersonExt.persnr. The PersonExt contains additional information about each person.
Person.Workarea refers to Workareas.Code. Workareas contains information about where the people are working. The Workareas table also contains a reference (workareas.location) to Locations.id, so that address information can be tied to a certain work area.
Now what I want to do is get a persons information, extended information, workarea information and the address info from that workarea, preferably in one single query.
I tried the following:
SELECT *
FROM persons AS P, personsext AS PE, workareas AS W, Locations AS L
WHERE P.persnr=PE.persnr And
W.code=P.workarea And
L.id=W.location;
However, whenever there's no matching PE.persnr, W.code or L.id the record isn't shown. I don't want all this additional information to be required so joins are required. So I tried the following:
SELECT *
FROM persons AS P
LEFT JOIN personsext AS PE ON P.persnr=PE.persnr
LEFT JOIN workareas AS W ON P.workarea=W.code
LEFT JOIN locations AS L ON W.location=L.id
but I get a syntax error with that. So how do I do this?
Person
persnr
name
workarea
PersonExt
persnr
Workareas
code
region
unit
location
Locations
id
Address
Street
City
The bold text is the database name with the fieldnames under it. The Person table contains information about different persons. Person.persnr refers to PersonExt.persnr. The PersonExt contains additional information about each person.
Person.Workarea refers to Workareas.Code. Workareas contains information about where the people are working. The Workareas table also contains a reference (workareas.location) to Locations.id, so that address information can be tied to a certain work area.
Now what I want to do is get a persons information, extended information, workarea information and the address info from that workarea, preferably in one single query.
I tried the following:
SELECT *
FROM persons AS P, personsext AS PE, workareas AS W, Locations AS L
WHERE P.persnr=PE.persnr And
W.code=P.workarea And
L.id=W.location;
However, whenever there's no matching PE.persnr, W.code or L.id the record isn't shown. I don't want all this additional information to be required so joins are required. So I tried the following:
SELECT *
FROM persons AS P
LEFT JOIN personsext AS PE ON P.persnr=PE.persnr
LEFT JOIN workareas AS W ON P.workarea=W.code
LEFT JOIN locations AS L ON W.location=L.id
but I get a syntax error with that. So how do I do this?