【问题标题】:Join with case statement in tsql在sql中加入case语句
【发布时间】:2018-03-14 19:10:48
【问题描述】:

我有桌子:

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

【问题讨论】:

  • 编辑您的问题并包含完全限定的列名,以便清楚列的来源。
  • on (Direction = 1 and myTable3.TypeId = myTable1.TypeId) or (Direction != 1 and myTable3.TypeId = myTable2.TypeId)

标签: sql tsql


【解决方案1】:

CASE 表达式的谓词(即CASE 表达式生成的内容)不能是相等条件,而必须是一个值。您可以将最终连接条件编写如下:

INNER JOIN MyTable3 t3
    ON (Direction = 1 AND t3.TypeId = t1.TypeId) OR
       (Direction <> 1 AND t3.TypeId = t2.TypeId)

这是完整的查询:

SELECT 
    Root,
    Direction,
    Type
FROM MyTable t
INNER JOIN MyTable1 t1
    ON t1.Id = t.RootId
INNER JOIN MyTable2 t2
    ON t2.Id = t.RootId
INNER JOIN MyTable3 t3
    ON (Direction = 1 AND t3.TypeId = t1.TypeId) OR
       (Direction <> 1 AND t3.TypeId = t2.TypeId);

【讨论】:

    【解决方案2】:

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

    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;
    

    使用orcase(或在on 子句中使用and 以外的任何内容)会对性能产生很大影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多