【发布时间】:2015-02-15 05:01:51
【问题描述】:
我有两个要加入的表,Table1 和 Table2。每个表都有两个唯一的键,我们称它们为 Key1 和 Key2。我想要做的是 LEFT JOIN Table2 to Table1,其中任何键都匹配四种可能组合中的任何一种:
- Table1.Key1 = Table2.Key1
- Table1.Key1 = Table2.Key2
- Table1.Key2 = Table2.Key1
- Table1.Key2 = Table2.Key2
我的问题是:有没有有效的方法来做到这一点?现在我想出了类似的东西,但它需要很长时间才能运行。
CREATE TABLE NEW_TABLE AS
SELECT a.*,
CASE WHEN a.Key1 = b.Key1 THEN 1 ELSE 0 END AS match1,
CASE WHEN a.Key1 = c.Key2 THEN 1 ELSE 0 END AS match2,
CASE WHEN a.Key2 = b.Key1 THEN 1 ELSE 0 END AS match3,
CASE WHEN a.Key2 = c.Key2 THEN 1 ELSE 0 END AS match4
FROM Table1 a
LEFT JOIN (Select Key1 From Table2 Where Key1 is not null) b
on a.Key1 = b.Key1 or a.Key2 = b.Key1
LEFT JOIN (Select Key2 From Table2 Where Key2 is not null) c
on a.Key1 = c.Key2 or a.Key2 = c.Key2
;
没救了,我知道...
编辑:示例数据和所需结果如下:
表 1:
Key1 Key2 Sales Revenue
qwer!@ dhfgfw 455 30005
asdf#$ dfg654 221 28711
edfr2# gg%%^f 213 31667
gthy!2 awd^&5 133 13345
rf$#22 34ffgg 655 41237
bhjk%g w3erff 122 10066
f&*yhj dffghj 126 11004
表 2:
Key1 Key2
qwer!@ {null}
{null} dfg654
ffgww2 ppolkk
{null} gthy!2
jjjj33 l00kjl
nmnmnm 34ffgg
awd^&5 {null}
期望的结果:
Key1 Key2 Sales Revenue match1 match2 match3 match4
qwer!@ dhfgfw 455 30005 1 0 0 0
asdf#$ dfg654 221 28711 0 0 0 1
edfr2# gg%%^f 213 31667 0 0 0 0
gthy!2 awd^&5 133 13345 1 0 1 0
rf$#22 34ffgg 655 41237 0 0 0 1
bhjk%g w3erff 122 10066 0 0 0 0
f&*yhj dffghj 126 11004 0 0 0 0
【问题讨论】:
-
您能否发布一个数据示例以及您希望达到的结果?
-
不知道这是否真的有帮助,但如果您有任何相关索引,我建议您加入实际表而不是子查询。你这样做的方式(我认为)会让你很难使用这些表上的任何索引。
标签: sql oracle performance left-join