加入tsql

时间:2018-03-14 11:04:32

标签: sql tsql

我有桌子:

CREATE TABLE MyTable (
    RootId int,
    Direction bit,
   ....
);

现在,我必须从这个表中编写select并将一些表连接到它。连接表取决于Direction参数。如何像这里一样加入MyTable3:

 select 
  Root,
  Direction,
  Type
 from MyTable
 join MyTable1 on 
   MyTable1.Id = RootId
 join MyTable2 on 
   MyTable2.Id = RootId

 join MyTable3 on 
   ...
   case select when Direction = 1
     MyTable3.TypeId = MyTable1.TypeId
   else
     MyTable3.TypeId = MyTable2.TypeId

2 个答案:

答案 0 :(得分:4)

\"%%~d1\\\"表达式的谓词(即7表达式生成的内容)不能是相等条件,而是必须是值。您可以按如下方式编写最终连接条件:

CASE

以下是完整查询:

CASE

答案 1 :(得分:1)

出于性能原因,您可能希望使用两个left join,如下所示:

select Root,Direction,
      coalesce(m3_1.Type, m3_2.Type) as type
from MyTable join
     MyTable1 
     on MyTable1.Id = MyTable.RootId join
     MyTable2
     on MyTable2.Id = MyTable.RootId left join
     MyTable3 m3_1
     on m3_1.Direction = 1 and
        m3_1.TypeId = MyTable1.TypeId left join
     MyTable3 m3_0
     on m3_2.Direction = 1 and
        me_2.TypeId = MyTable2.TypeId;

or子句中使用caseand(或on以外的任何其他内容)会对性能产生重大影响。