LEFT外连接+ where子句意外结果

时间:2016-08-01 19:39:21

标签: sql sql-server

我对查询结果感到惊讶,希望有人能解释一下。

查询有点大,所以我把它提炼到关键部分:

SELECT * 
FROM  A 
INNER JOIN B ON A.id = B.id
LEFT JOIN C ON C.ID = B.ID
WHERE A.Dt = '2016-06-23' 
  AND (B.StatusCode=' ' OR C.Code <> 9) 

我得到的日期不是6/23/16,即使我在where子句中也有。我认为它与在一个表达式中将Left连接表和内连接表中的where子句中的列组合在一起,但之前从未经历过这种情况。

更新:添加实际查询

SELECT *
FROM CERT2.cube_mbbal_Daily_Balances BAL
INNER JOIN CERT.Dim_Account A ON A.AccountKey = BAL.AccountKey
LEFT JOIN CERT2.Dim_LoanAccount LA ON A.AccountKey = LA.AccountKey
WHERE 
    (A.AccountClassification IN ('Checking', 'Savings')
     AND AccountStatus IN ('1', '3', '5', '6', '7'))
    OR 
    (A.AccountClassification IN ('Time')
     AND AccountStatus IN ('1', '5', '7'))
    OR 
    (A.AccountClassification IN ('Loan')
     AND (AccountStatus <> 'C' OR RiskCode <> 9))
    AND BAL.DateOfFinancialMeasure = 20160623

1 个答案:

答案 0 :(得分:1)

AND之前评估

OR。这就像您正在评估2 + 5 + 7 * 5并想知道为什么您获得42而不是70

尝试:

select *
from CERT2.cube_mbbal_Daily_Balances BAL
inner join CERT.Dim_Account A
    on A.AccountKey = BAL.AccountKey
left join CERT2.Dim_LoanAccount LA
    on A.AccountKey = LA.AccountKey
where (
           (A.AccountClassification in ('Checking', 'Savings') and AccountStatus in ('1', '3', '5', '6', '7'))
        or (A.AccountClassification in ('Time') and AccountStatus in ('1', '5', '7'))
        or (A.AccountClassification in ('Loan') and (AccountStatus <> 'C' or RiskCode <> 9))
    )
    and BAL.DateOfFinancialMeasure = 20160623