仅当列值为true时才加入表

时间:2009-01-14 15:55:30

标签: sql sql-server

我正在使用SQL Server 2005.我正在尝试将两个表连接在一起,但仅当主表中的列值为true时。像这样:

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'

T1中有一个列值,表示我是否必须使用T2中的值。我可以围绕where子句,但它总是会连接到表,如果T1中的值为false,则T2中没有要加入的值,因此select不返回任何行。

你不能在联盟中加上一个案例,所以我对此有点困惑......任何人都可以帮忙吗?

6 个答案:

答案 0 :(得分:3)

select * 
from T1
join T2 
  on  T1.value = T2.value
  and T1.booleancolumn = 1
where T2.value2 = 'variable2'
and T2.value3 = 'variable3';

答案 1 :(得分:1)

类似于Dave发布的内容,但我也读到这意味着你想要在结果中实际替换值。在那种情况下:

SELECT
    COALESCE(T2.Value, T1.Value) AS Value, 
    COALESCE(T2.Value2, T1.Value2) AS Value2,
    COALESCE(T2.Value3, T1.Value3) AS Value3
FROM T1
LEFT JOIN T2 ON T2.value = T1.value 
    AND T2.Value2= @Variable2 AND T2.Value3 = @Variable3

请注意,我也将你的常数视为真正的变量。

答案 2 :(得分:0)

也许我误解了你的问题,但这是我的猜测。

认为你可以在WHERE中使用案例。

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = case T1.useT2 when 'yes' then 'variable2' else T2.value2 END
and T2.value3 = case T1.useT2 when 'yes' then 'variable3' else T2.value3 END

答案 3 :(得分:0)

非常类似于Dave说的,虽然我会将booleancolumn检查放入WHERE,所以这样的事情

SELECT * FROM T1
INNER JOIN T2 
  ON T1.Value = T2.Value
WHERE T2.Value2 = 'variable2'
AND T2.Value3 = 'variable3'
AND T1.booleancolumn = 1

答案 4 :(得分:0)

Dave Marke是对的,但更为一般......

条件联接是您的问题的答案,请尝试在网上找到一些资源,例如

http://weblogs.sqlteam.com/jeffs/archive/2007/04/03/Conditional-Joins.aspx

http://bytes.com/groups/ms-sql/641690-difference-condition-join-where

根据表格中的数据进行连接是非常强大的技术

答案 5 :(得分:0)

如果有的话,有关条件连接的性能考虑因素,我想知道吗?它是否相当于这样的UNION:

SELECT T1.* 
  FROM T1
  WHERE T1.use_t2 = FALSE
  AND T1.value2 = 'variable2'
  AND T1.value3 = 'variable3'
UNION ALL
SELECT T2.* 
  FROM T1 JOIN T2 ON T1.value = T2.value
  WHERE T1.use_t2 = TRUE
  AND T2.value2 = 'variable2'
  AND T2.value3 = 'variable3'