|
Subject:
|
join
|
|
Posted By:
|
erin
|
Post Date:
|
10/24/2003 3:00:24 PM
|
I have the following tables:
Table1: ORG A B C D ------------------- Table2: ORG Num1 A 5 -------------------- Table3: ORG Num2 A 2 D 3 -------------------- Table4: ORG Num3 B 1 D 7 -------------------- Table5: ORG Num4 B 4 C 3
I would like to join all the records without any duplicate data.
I would like to create the following table: ORG Num1 Num2 Num3 Num4 A 5 2 0 0 B 0 0 1 4 C 0 0 0 3 D 0 3 7 0
Thanks for your help...
|
|
Reply By:
|
nikolai
|
Reply Date:
|
10/24/2003 3:29:01 PM
|
Well, you'll need to use left joins because you're connecting tables where the org value doesn't exist in ALL tables, so the join must create NULL for the num columns for the tables in which a corresponding ORG value doesn't exist.
SELECT table1.ORG, table2.num1, table3.num2, table4.num3, table5.num4
FROM table1
LEFT JOIN table2 ON table1.org = table2.org
LEFT JOIN table3 ON table1.org = table3.org
LEFT JOIN table4 ON table1.org = table4.org
LEFT JOIN table5 ON table1.org = table5.org
Should do it, though you'll get NULL values, not zeros, for the numbers where the ORG value doesn't exist in the table.
Take care,
Nik http://www.bigaction.org/
|
|
Reply By:
|
Jeff Mason
|
Reply Date:
|
10/25/2003 8:18:13 AM
|
You could wrap each result column in a COALESCE statement to translate the NULL values to a 0:
SELECT table1.ORG, COALESCE(table2.num1,0) as NUM1,
COALESCE(table3.num2,0) as NUM2, COALESCE(table4.num3,0) as NUM3,
COALESCE(table5.num4,0) as NUM4)
FROM ...
Jeff Mason Custom Apps, Inc. www.custom-apps.com
|
|
Reply By:
|
erin
|
Reply Date:
|
10/27/2003 12:37:35 PM
|
Thank you all. I did not mentioned that I have been working on access not mysql. I used IIF(ISNULL.... ) function instead of COALESCE. My program is working fine now.
Thanks again...
|
|
Reply By:
|
Jeff Mason
|
Reply Date:
|
10/27/2003 2:37:38 PM
|
I think the nz function will do what you want, a bit simpler - e.g.
SELECT SELECT table1.ORG, nz(table2.num1,0) as NUM1,
...
Jeff Mason Custom Apps, Inc. www.custom-apps.com
|