Thursday, October 3, 2013

How to merge 3 tables by the field from 4th table


This does not work... I get Cartesian product of TAB_A, TAB_B and TAB_C



The query below uses the same sample data you posted above. Can you please check this and let me know how is this different in terms of the result of this query and the expected output you posted above?



SELECT TableMain.ID_Main,TableMain.Main_Data,Tab_A.Data_A,Tab_B.Data_B,tab_c.Data_C FROM
(VALUES(1, 'main1'), (2,'main2'), (3,'main3') ) TableMain(ID_Main,Main_Data)
LEFT JOIN
(VALUES(1, 2, 'A2'), (2,3,'A3') ) Tab_A(ID_A,ID_Main,Data_A) ON TableMain.ID_Main = Tab_A.ID_Main
LEFT JOIN
(VALUES(1, 1, 'B3'), (2,1,'B3_1') ) Tab_B(ID_B,ID_Main,Data_B) ON TableMain.ID_Main = Tab_B.ID_Main
LEFT JOIN
(VALUES(1, 3, 'C3') ) Tab_C(ID_C,ID_Main,Data_C) ON TableMain.ID_Main = Tab_C.ID_Main





--sIbu


No comments:

Post a Comment