Left Joins... - Mailing list pgsql-sql

From Michael Richards
Subject Left Joins...
Date
Msg-id 3B1183A2.000107.09275@frodo.searchcanada.ca
Whole thread Raw
List pgsql-sql
I've got a select that pulls many values from the same table. 
Basicaly for a given formid there can be many fields each one 
depending on a definition. So form1 may be broken down as follows:
fieldid      1      firstname 2      lasname 3      postal code

Rather than sticking this data in XML (which is hard to query and 
index) Each one occupies a row in my formdata table.

I've got a nasty query that joins a table onto itself like 22 times. 
I'm wondering if there might be a better way to do this, and also how 
I can left join every additional table on the first one. By this I 
mean that if f1 matches my criteria and therefore isn't null, then 
every other joined field will occur, null or not...

Here is a snippet of my query so you can see what I'm doing:
SELECT 
f1.strval,f2.strval,f3.strval,f4.strval,f5.strval,f6.strval,f7.strval,
f8.strval,f9.strval,f10.strval,f11.strval,f12.strval,f13.strval,f14.st
rval
,f15.strval,f16.strval,f17.strval,f18.strval,f19.strval,f20.strval,m1.
strval FROM formdata AS f1   LEFT JOIN formdata AS f2 ON (f2.formid=4 AND f2.occid=1 AND 
f2.fieldid=2 AND f2.userid=f1.userid)   LEFT JOIN formdata AS f3 ON (f3.formid=4 AND f3.occid=1 AND 
f3.fieldid=3 AND f3.userid=f1.userid)   LEFT JOIN formdata AS f4 ON (f4.formid=4 AND f4.occid=1 AND 
f4.fieldid=4 AND f4.userid=f1.userid)   LEFT JOIN formdata AS f5 ON (f5.formid=4 AND f5.occid=1 AND 
f5.fieldid=5 AND f5.userid=f1.userid)   LEFT JOIN formdata AS f6 ON (f6.formid=4 AND f6.occid=1 AND 
f6.fieldid=6 AND f6.userid=f1.userid)   LEFT JOIN formdata AS f7 ON (f7.formid=4 AND f7.occid=1 AND 
f7.fieldid=7 AND f7.userid=f1.userid)   LEFT JOIN formdata AS f8 ON (f8.formid=4 AND f8.occid=1 AND 
f8.fieldid=8 AND f8.userid=f1.userid)   LEFT JOIN formdata AS f9 ON (f9.formid=4 AND f9.occid=1 AND 
f9.fieldid=9 AND f9.userid=f1.userid)
[...]

So I don't care if f2..f22 do not exist, but f1 must exist...

Any ideas?

-Michael
_________________________________________________________________    http://fastmail.ca/ - Fast Free Web Email for
Canadians

pgsql-sql by date:

Previous
From: Torsten Knodt
Date:
Subject: Is it possible to defer triggers?
Next
From: Palle Girgensohn
Date:
Subject: Column reference X is ambiguous?