首页 > 解决方案 > 左外连接返回多条记录

问题描述

以下查询返回重复/多条记录。有没有办法在 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)

标签: mysql

解决方案


  • 您想要 rtable 中的所有行和 etable 中的所有行。
  • 您希望 ttable 中的那些行在前两个表中没有匹配项。
  • 您希望 ftable 中的那些行在前三个表中没有匹配项。
  • 您想要那些在前四个表中不匹配的来自 stable 的行。

并且您认为 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 行,我不知道为什么。好吧,如果这是您需要的,您可能可以相应地更改我的查询。

演示:http ://sqlfiddle.com/#!9/ae1a69/1


推荐阅读