我试图简化或加快以下查询:

时间:2017-08-28 16:53:24

标签: sql sql-server

create table table_3 as     
select *
from table_1 
   join table_2 on tbl.1.C1 = tbl.2.C1
or tbl.1.C1 = tbl.2.C2 
or tbl.1.C1 = tbl.2.C3
or tbl.1.C1 = tbl.2.C4
or tbl.1.C1 = tbl.2.C5
or tbl.1.C1 = tbl.2.C6

表2中总共有10列我需要检查。基本上,我想检查表2中的表1值,如果表2 column1为Null或不匹配,请查看表2 column2,如果null或不匹配,请查看表2 column3 ....

4 个答案:

答案 0 :(得分:2)

我不知道我是否理解您的查询,您可以尝试一下:

selectionStart

在这段代码中首先尝试查找table_2.c1的值,如果为null则尝试table_2.c2的值.....

答案 1 :(得分:1)

我在这里猜测你要做什么,因为你的帖子不清楚。我想你想在table2中的任何列列表与table1中的值匹配时加入。这是一个很大的迹象,表明你的设计中有些东西很漂亮,但查询很简单。这样的事情。

select *
from Table1 t1
join Table2 t2 on t1.C1 in (t2.C1, t2.C2, t2.C3, t2.C4, t2.C5)

答案 2 :(得分:0)

可能正常化/取消数据然后加入?

select *
from table_1  t1
join (Select c1 as cNorm, differentID_# from table_2 UNION ALL 
      Select c2, differentID_# from table_2 UNION ALL 
      Select c3, differentID_# from table_2 UNION ALL 
      Select c4, differentID_# from table_2 UNION ALL
      Select c5, differentID_# from table_2 UNION ALL
      Select c6, differentID_# from table_2 UNION ALL
      Select c7, differentID_# from table_2 UNION ALL
      Select c8, differentID_# from table_2 UNION ALL
      Select c9, differentID_# from table_2 UNION ALL
      Select c10, differentID_# from table_2) t2
 on t1.c1 = t2.cNorm

这将匹配任何值,并且不会从c1-c10进展。

答案 3 :(得分:0)

or语句中的

join可能会导致性能下降。目前还不清楚你真正想做什么,但以下可能会产生更好的优化计划:

select *
from table_2 t2 join
     table_1 t1
     on t1.C1 = t2.C1
union all
select *
from table_2 t2 join
     table_1 t1
     on t1.c1 = t2.c2 and t1.c1 not in (t2.c1)
union all
select *
from table_2 t2 join
     table_1 t1
     on t1.c1 = t2.c3 and t1.c1 not in (t2.c1, t2.c2)
. . .