过滤左连接sql

时间:2013-04-12 09:09:39

标签: sql tsql

我有这个SQL查询:

SELECT Customer.IDCustomer, Customer.Name,
Sign.IdSign, Sign.Name, Sign.Delete
FROM Customer
LEFT JOIN  Sign_Customer ON Sign_Customer.IDCustomer=Customer.IDCustomer 
     AND  ( SELECT CAST(CASE WHEN S_C.Delete=0 OR S_C.Delete is Null THEN 1 ELSE 0 END AS BIT )
            FROM Sign AS S_C
            WHERE S_C.IdSign=Sign_Customer.IdSign)=1
LEFT JOIN Sign ON Sign.IdSign=Sign_Customer.IdSign

ORDER BY Customer.Name

此查询工作正常,但我想知道是否存在另一种方法来过滤我的第一个左连接而不使用SELECT CAST ...条件。


更新

抱歉,我没有在结果中解释我想要的内容:

  • 我所有没有签名的客户
  • 我的所有客户都启用了Sign

如果没有启用Sign,则具有禁用Sign的客户不会显示或显示为“without Sign”。

例: 我的客户表

IDCustomer   | Name
1            | Customer 1
2            | Customer 2
3            | Customer 3
4            | Customer 4

Sign_Customer:

IDCustomer   | IdSign
1            | 1
3            | 2
3            | 3
3            | 5
4            | 4

登录

IdSign       | Name         | Delete
1            | Sign1        | 0
2            | Sign2        | 1
3            | Sign3        | 0
4            | Sign4        | 1
5            | Sign5        | 0

结果

Customer.IDCustomer | Customer.Name  | Sign.IdSign | Sign.Name | Sign.Delete
1                   | Customer 1     | 1           | Sign1     | 0
2                   | Customer 2     | null        | null      | null
3                   | Customer 3     | 3           | Sign3     | 0
3                   | Customer 3     | 5           | Sign5     | 0
4                   | Customer 4     | null        | null      | null

3 个答案:

答案 0 :(得分:0)

SELECT Customer.IDCustomer, Customer.Name, Sign.IdSign, Sign.LibEnseigne, Sign.Delete
FROM Customer
LEFT JOIN  Sign_Customer ON Sign_Customer.IDCustomer=Customer.IDCustomer 
LEFT JOIN Sign ON Sign.IdSign=Sign_Customer.IdSign
AND (S_C.Delete=0 OR S_C.Delete is Null)
ORDER BY TEnseigne.NomEnseigne, Customer.Name

答案 1 :(得分:0)

以下情况如何?

   SELECT Customer.IDCustomer
        , Customer.Name
        , Sign.IdSign
        , Sign.Name
        , Sign.Delete
     FROM Customer
LEFT JOIN Sign_Customer
     JOIN Sign
       ON Sign_Customer.IdSign = Sign.IdSign
      AND Sign.Delete = 0
       ON Customer.IDCustomer = Sign_Customer.IDCustomer
 ORDER BY Customer.NAME;

答案 2 :(得分:0)

我相信这符合您的标准:

SELECT Customer.IDCustomer, Customer.Name,
Sign.IdSign, Sign.Name, Sign.Delete
FROM Customer
LEFT JOIN (
  select Sign_Customer.*
  from Sign_Customer
  join Sign on S_C.IdSign=Sign_Customer.IdSign
  where isnull(S_C.Delete,0) = 0
) Sign_Customer ON Sign_Customer.IDCustomer=Customer.IDCustomer 
LEFT JOIN Sign ON Sign.IdSign=Sign_Customer.IdSign    
ORDER BY Customer.Name