I have a table attach with huge data sets, it is a temp table and created by sql:
id number name
1 X1 name1
2 X2 name2
3 X3 name3
4 X4 name4
table attachment_map
id item attach_id file_id versionid
1 X1 1 100 0
2 X2 0 0 1
table version
id attach_id
1 2
I want to have query to get:
id number name item
1 X1 name1 X1
2 X2 name2 X2
3 X3 name3
4 X4 name4
As you can see, the return rows added new column which actually got from table attachment_map, there have three impossibles:
1).attach don’t have item.
2).Have item, by connecting to column attach_id of attachment_map.
2).Have item, by connecting to column attach_id of version.
I wrote a query but having poor performance, executed it slowly and it seems because of union. can everybody tell another way or how I can improvee it? thanks
WITH tb AS
(SELECT t.*,
i.item
FROM attach t,
attachment_map am,
version v
WHERE (am.attach_id = t.attachid
OR (am.file_id = 0
AND am.version_id = v.id))
)
SELECT * FROM tb
UNION
SELECT tb.*, NULL FROM tb, attach WHERE tp.id NOT IN (attach.id);
Use two
LEFT OUTER JOINs to link the three tables, and thenCASEtheitemfields in the order of priority (first inspect attach, then attachment_map, then version).