以下查询返回重复/多条记录。有没有一种方法可以对SW.MTableId的不同ID进行第二次左联接。
SELECT SW.* from
(SELECT * FROM Stable SD,MTable MT WHERE SD.ID=1234 AND SD.ID=MT.Stable_ID) SW
LEFT OUTER JOIN TTable TD ON (TD.MTable_ID=SW.MTableId AND TD.STATUS='ACTIVE')
LEFT OUTER JOIN PTable PT ON (PT.MTable_ID=SW.MTableId AND PT.TTable_ID IS NULL)
enter code here
重复的行:
SW.MTableId TD.MTable_ID PT.MTable_ID
71878 67048 849230
71878 67046 849230
71878 67047 849230
71878 67039 849230
71878 67038 849230
71878 67045 849230
71878 67037 849230
http://sqlfiddle.com/#!9/5a127b/2创建了带有完整表定义的小提琴,要求我们需要执行查询才能从每个表中获取主键列。
Stable can be direct parent of Ftable, Ttable, Etable, Rtable.
Ftable can be direct parent of Ttable, Etable only.
Ttable can be direct parent of Etable, Rtable.
Etable can be direct parent of Rtable.
#预期结果
Sid Fid Tid Eid Rid
2 12 103 203 303
2 12 103 203 304
1 null 101 null 302
3 null null null 301
1 10 null 202 null
1 null null 201 null
1 null 102 null null
1 11 null null
Stable
sid, sname
1, 'S1'
2, 's2'
3, 's3'
Ftable
fid, fname, sid
10, 'f1', 1
11, 'f2', 1
12, 'f3', 2
Ttable
tid, tname, fid, sid
101, 't1', null, 1
102, 't2', null, 1
103, 't3', 12, 2
Etable
eid, ename, tid , fid, sid
201, 'e1', null, null, 1
202, 'e2', null, 10, 1
203, 'e3', 103, 12, 2
Rtable
(rid, rname eid tid sid)
(301, 'r1' null null 3)
(302, 'r2' null 101 1)
(304, 'r4' 203, 103 2)
(303, 'r3' 203, 103 2)
答案 0 :(得分:0)
您认为null为值,即您认为null = null是匹配项。
这是逐步进行查询的查询。
select sid, null as fid, tid, eid, rid from rtable
union all
select sid, fid, tid, eid, null as rid from etable
union all
select sid, fid, tid, null as eid, null as rid from ttable
where (sid, coalesce(fid, -1), coalesce(tid, -1)) not in
(select sid, coalesce(fid, -1), coalesce(tid, -1) from etable)
and (sid, coalesce(fid, -1), coalesce(tid, -1)) not in
(select sid, -1, coalesce(tid, -1) from rtable)
union all
select sid, fid, null as tid, null as eid, null as rid from ftable
where (sid, coalesce(fid, -1)) not in
(select sid, coalesce(fid, -1) from ttable)
and (sid, coalesce(fid, -1)) not in
(select sid, coalesce(fid, -1) from etable)
and (sid, coalesce(fid, -1)) not in
(select sid, -1 from rtable)
union all
select sid, null as fid, null as tid, null as eid, null as rid from stable
where sid not in (select sid from ftable)
and sid not in (select sid from ttable)
and sid not in (select sid from etable)
and sid not in (select sid from rtable)
order by sid, fid, tid, eid, rid;
结果几乎是您所要求的。只是,您将sid 2的rtable和etable行合并,但我不知道为什么。好吧,如果这是您的需要,则可以相应地更改我的查询。