使用不同列在sql中使用条件ON(连接条件)

时间:2014-09-08 22:41:29

标签: sql sql-server logic

我需要使用条件ON子句,如果if为true,则需要放置不同的列条件,如果为false则需要 这是示例

select a.* b.*
 from tblA a inner join tblB b
 on a.somefield = b.someOtherField
 AND 
 /*THIS IS WHERE THE PROBLEM STARTS, I am using pseudo code, and need help with the actual code
 (
   if substring(a.field3, 1,3) <>'' - I want to use substring(a.field3, 1,3)=b.field2
   else, I want to use say b.field5='Y'
 )
 */

因此,在IF评估为真的情况下,我想要选择这种类型:

select a.* b.*
 from tblA a inner join tblB b
 on a.somefield = b.someOtherField
 **AND substring(a.field3, 1,3)=b.field2**

如果condition为false,我希望有效的join子句是

    select a.* b.*
 from tblA a inner join tblB b
 on a.somefield = b.someOtherField
 **AND b.field5='Y'**

使用SQL Server

由于

1 个答案:

答案 0 :(得分:1)

只需使用布尔逻辑:

select a.* b.*
from tblA a inner join
     tblB b
     on a.somefield = b.someOtherField AND
        ((substring(a.field3, 1, 3) <> '' and substring(a.field3, 1,3) = b.field2) or
         ( (substring(a.field3, 1, 3) = '' or a.field3 is null) and b.field5 = 'Y'
        );

为清楚起见,我在第二个子句中使用了substring()。它同样可以写成:

         (a.field3 = '' and b.field5 = 'Y')

因为如果子串是'',那么原始字符串也是如此。