[英]left outer join returning multiple records
以下查詢返回重復/多條記錄。 有沒有辦法對 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)
並且您認為 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 行,我不知道為什么。 好吧,如果這是您需要的,您可能可以相應地更改我的查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.