Question

Main Table : MT
===============
PK, C1, C2
==========
1, X, X
2, X, X
3, X, X
..........
100, X, X


Table 1 :T1
===============
PK, TC1
=======
2, D1
3, D1

Table 2: T2
===============
PK, TC2
=======
3, D2

Table 3: T3
===============
PK, TC3
=======
4, D3

Table 4: T4
===============
PK, TC4
=======
2, D4

I want output of Master Table after making some join or any how as below :

Master Table
===============
PK,C1,C2,TC1,TC2,TC3,TC4
========================
(1,X,X,null,null,null,null)
(2,X,X,D1,null,null,D4)
(3,X,X,D1,D2,null,null)
(4,X,X,null,null,D3,null)

I tried

select * from
MT inner join T1 on MT.PK=T1.PK
inner join T2 on MT.PK = T2.PK
inner join T2 on MT.PK = T3.PK
inner join T2 on MT.PK = T4.PK

But I am getting some rows duplicate. Even tried distinct still getting duplicate. I think there must be some other alternative to achieve this thing.

Était-ce utile?

La solution

The problem with your existing query is you are using an INNER JOIN between all of the tables. An INNER JOIN requires that the value of the column being joined on exists in both tables.

It seems to me that you want to use a LEFT JOIN instead:

select MT.PK, MT.C1, MT.C2, T1.TC1, T2.TC2, T3.TC3, T4.TC4
from MT 
left join T1 on MT.PK=T1.PK
left join T2 on MT.PK = T2.PK
left join T3 on MT.PK = T3.PK
left join T4 on MT.PK = T4.PK;

See SQL Fiddle with Demo

A LEFT JOIN will return all rows from the MT table and then the data from the other tables if it exists when the PK matches.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top