SQL JOIN和LEFT JOIN连接不同条件的同一个表

时间:2010-07-21 20:31:33

标签: sql sql-server sql-server-2005 dynamics-crm

我需要在满足某些条件时加入表格,并在满足其他条件时LEFT JOIN。由于我在带有过滤器的MS Dynamic CRM中,我不能使用UNION

   SELECT stuff.stuffs
     FROM MainTable    

JOINS othertable
LEFT JOIN othertables

LEFT JOIN TableX as X1 ON (Conditions1.1 = X1.1
                      AND MainTable.Type = 1)    
     JOIN TableX as X2 ON (Conditions2.2 = X2.2
                      AND MainTable.Type = 2)
  • 如果我注释掉X2部分,我会从X1部分得到我需要的东西,而不是X2部分。
  • 如果我LEFT JOIN X2部分,我在X2中有额外的信息。
  • 如果我这样离开,我从X2部分得到我需要的东西,但是X1没有。

我尝试了一些变种,但我无法达成令人满意的解决方案。

编辑:我的原始查询是这样的:

SELECT stuff.stuffs
     FROM MainTable

(LEFT) JOIN TableX as X1 
         ON (Conditions1.1 = X1.1
             AND MainTable.Type = 1)    
     OR 
         ON (Conditions2.2 = X2.2
             AND MainTable.Type = 2)

但如果它是左连接,我从X2获得额外的信息 和一个JOIN给我错过了X1的信息,

2 个答案:

答案 0 :(得分:1)

我想你需要尝试这个:

   SELECT stuff.stuffs
     FROM TABLEX x
LEFT JOIN MAINTABLE mt1 ON mt.1 = x.1
                       AND mt.type = 1
LEFT JOIN MAINTABLE mt2 ON mt.2 = x.2
                       AND mt.type = 2

答案 1 :(得分:1)

OP中所需的实际匹配并不明确,但您可以尝试以下方法:

Select stuff.stuffs
From MainTable
    Left Join TableX As X1
        On ( MainTable.Type = 1 And X1.1 = ...)
            Or ( MainTable.Type = 2 And X1.2 = ...)

鉴于您已添加到OP和注释中的内容,您仍然不清楚是否从TableX中寻找满足任一条件或仅满足其中一个条件的行。但是,为了完整起见,这两者都是:

任何条件:我上面的原始解决方案以及您添加到帖子中的解决方案。

唯一一个条件:

Select stuff.stuffs
From MainTable
    Left Join TableX As X1
        On X1.1 = ...
    Left Join TableX As X2
        On X2.2 = ...
Where ( MainTable.Type = 1 And X1.PK Is Not Null And X2.PK Is Null )
    Or ( MainTable.Type = 2 And X2.PK Is Not Null And X1.PK Is Null )

原始帖子中缺少的是从TableX到MainTable的任何外键引用概念。因此,通常,我会想到这样的事情:

Select stuff.stuffs
From MainTable
    Left Join TableX As X1
        On X1.FK = MainTable.PK
    Left Join TableX As X2
        On X2.FK = MainTable.PK
Where ( MainTable.Type = 1 And X1.Col1 = ...  And X2.PK Is Null )
    Or ( MainTable.Type = 2 And X2.Col1 = ... And X1.PK Is Null )