SQL Server:在表连接条件中使用逻辑(if语句)

时间:2014-07-19 12:01:12

标签: sql-server if-statement join conditional-statements

我想要基于每个表行中字段值的条件表连接标准。

类似的东西:

select * 
from t1 
join t2 on t1.product = t2.product
        and (
             IF (t1.export = 1)
             Begin
                t2.export in (0,1)
             Else Begin
               t2.export= 0
             END)

因此,根据表格行的值,相应地加入它。

一如既往地谢谢,

5 个答案:

答案 0 :(得分:3)

怎么样:

SELECT *
FROM t1 JOIN t2
    ON t1.product = t2.product
    AND (
        (t1.export = 1 AND t2.export IN (0, 1))
        OR (t1.export != 1 AND t2.export = 0)
    )

答案 1 :(得分:2)

由于t1.export的可能值只有0和1,因此您只需使用IN;

SELECT * 
FROM t1 
JOIN t2 
  ON t1.product=t2.product 
 AND t2.export IN (0, t1.export)

答案 2 :(得分:2)

编写此条件并确保仅按指定顺序评估所需条件的唯一方法是使用CASE语句,因为您无法确定执行条件,你不能指望SQL中的短路。

SELECT *
FROM t1
JOIN t2 ON t1.product=t2.product
AND CASE t1.export
        WHEN 1 THEN CASE
                        WHEN t2.export IN (0,
                                           1) THEN 1
                        ELSE 0
                    END
        ELSE CASE
                 WHEN t2.export = 0 THEN 1
                 ELSE 0
             END
    END = 1

您也可以按如下方式编写,但在这种情况下,条件可能会重新排序。它不会对结果产生任何影响,但是对于更复杂的条件,它可能会对性能产生影响。

AND (
    (t1.export = 1 AND t2.export IN (0, 1))
    OR (t1.export != 1 AND t2.export = 0)
)

答案 3 :(得分:1)

您可以使用条件语句:

select *
from   t1
join   t2
on     t1.product=t2.product
and    ( ( t1.export = 1 and t2.export in (0,1) )
         or
         ( t1.export != 1 and t2.export = 0 )
       )

答案 4 :(得分:1)

如果t1.export可以采用NULL值,则等效逻辑为:

on t1.product = t2.product and
   ((t1.export = 1 and t2.export in (0, 1)) or
    (t1.export <> 1 and t2.export = 0) or
    (t1.export is null and t2.export = 0)
   )

或者,或者:

on t1.product = t2.product and
   (t2.export = 0 or
    t1.export = 1 and t2.export = 1
   )