I need help in avoiding joining same table multiple times. Here is my sample query.
Table1 have 3 columns ABC_ID,DEF_ID,XYZ_ID and is associated to table2 on ID column . 3 column values in table1 can be null and If values are present then i need to return associated value from table 2 using different column names as in select statement.
As i am using left join i ended up joining table2 three times with table1 on each type if ID column which is having lot of performance issues. How can i write this in different way to avoid join multiple times. Here is sample data. Any help is appreciated
select
(
CASE
WHEN ( table2.ID = table1.ABC_ID)
THEN table2.ID_VAL
ELSE 'TEST1'
END ) AS "TEST1",
(
CASE
WHEN (table2a.ID = table1.DEF_ID)
THEN table2a.ID_VAL
ELSE 'TEST2'
END ) AS "TEST2",
(
CASE
WHEN (table2b.ID = table1.XYZ_ID)
THEN table2b.ID_VAL
ELSE 'TEST3'
END ) AS "TEST3"
from table1 table1
left join table2 table2 on (table2.ID=table1.ABC_ID)
left join table2 table2a on ( table2a.id=table1.DEF_ID)
left join table2 table2b on ( table2b.id=table1.XYZ_ID)
where table1.Id_NUM='1'
Table1
Id_NUM ABC_ID DEF_ID XYZ_ID
1 12345 456789 32145
2 null 456789 32145
3 12345 null null
Table2
ID ID_VAL
12345 abcded
456789 kjwsddk
321456 wedfgfv
OUTPUT
TEST1 TEST2 TEST3
12345 456789 32145
Your join
s are fine, but the query can be simplified:
select coalesce(t2a.ID_VAL, 'TEST1') as test1,
coalesce(t2d.ID_VAL, 'TEST2') as test2,
coalesce(t2x.ID_VAL, 'TEST3') as test3
from table1 t1 left join
table2 t2a
on t2a.ID = t1.ABC_ID left join
table2 t2d
on t2d.id = t1.DEF_ID left join
table2 t2x
on t2x.id = t1.XYZ_ID
where t1.Id_NUM = 1;
Notes:
id_num
is a number, so don't use single quotes for the value. case
expressions can be replaced by coalesce()
, which is simpler (this is not exactly the same if id_val
can be NULL
, but I'm guessing that doesn't happen). There is no reason to avoid joining the table three times. That is what your data model requires, because you have three separate foreign key references.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.