选择SQL JOIN失败的值

时间:2013-02-21 17:32:58

标签: sql sql-server tsql

目前,为了弄清楚SQL中连接失败的值,我使用以下方法

SELECT DISTINCT ACC.Name
     ,ACC.Area
     ,CASE
          WHEN A.Area IS NULL AND N.Name IS NULL
               THEN 'Name and Area do not match'
          WHEN A.Area IS NULL 
               THEN 'Area does not match'
          WHEN N.Name IS NULL
               THEN 'Name is null'
          ELSE 
               'Yes'
          END as IsTopAccount
 FROM Test.dbo.Accounts ACC
 LEFT JOIN Test.dbo.TopAccounts A ON A.Area = ACC.Area
 LEFT JOIN Test.dbo.TopAccounts N ON N.Name = ACC.Name

在上文中,必须在区域和名称上将帐户加入TopAccounts表。我需要两个连接来测试case语句中的每个条件。

是否有可能更有效地测试case语句中的每个条件,可能只有一个LEFT JOIN而不是两个单独的LEFT JOIN

请参阅此sql fiddle

3 个答案:

答案 0 :(得分:3)

我想这会奏效:

SELECT ACC.Name
     ,ACC.Area
     ,CASE
          WHEN T.Area IS NULL AND T.Name IS NULL
               THEN 'Not matching at all'
          WHEN T.Area != ACC.Area
               THEN 'Matching for name only'
          WHEN T.Name != ACC.Name
               THEN 'Matching for area only'
          ELSE 
               'Yes'
          END as IsTopAccount
 FROM A ACC
         LEFT JOIN TA T ON T.Area = ACC.Area 
                                        OR T.Name = ACC.Name

答案 1 :(得分:2)

你可以用两个来做:

SELECT ACC.Name
     ,ACC.Area
     ,CASE
          WHEN A.Area IS NULL AND N.Name IS NULL
               THEN 'Name and Area do not match'
          WHEN A.Area IS NULL 
               THEN 'Area does not match'
          WHEN N.Name IS NULL
               THEN 'Name is null'
          ELSE 
               'Yes'
          END as IsTopAccount
 FROM Test.dbo.Accounts ACC
 LEFT JOIN Test.dbo.TopAccounts A ON A.Area = ACC.Area
 LEFT JOIN Test.dbo.TopAccounts N ON N.Name = ACC.Name

答案 2 :(得分:2)

如果我理解了您的问题,我认为单个 FULL OUTER JOIN 会从两个表中提供不匹配的记录 null 结果。 Fiddle-Demo

SELECT A.Name ,A.Area
      ,CASE
          WHEN TA.Area IS NULL AND TA.Name IS NULL
               THEN 'Name and Area do not match'
          WHEN A.Area IS NULL 
               THEN 'Area does not match'
          WHEN TA.Name IS NULL
               THEN 'Name is null'
          ELSE 
               'Yes'
          END as IsTopAccount
 FROM A  FULL OUTER JOIN  TA 
      ON TA.Area = A.Area AND TA.Name = A.Name

您可以根据需要更改CASE以从两个表中检查null。这里有一些好visual examples about joins

根据评论,单个LEFT JOIN Fiddle-Demo

的结果相同
SELECT DISTINCT A.Name ,A.Area,
          CASE WHEN TA.Area IS NULL AND TA.Name IS NULL
               THEN 'Name and Area do not match'
          WHEN TA.Area <> A.Area 
               THEN 'Area does not match'
          WHEN TA.Name <> A.Name
               THEN 'Name is does not match'
          ELSE 'Yes' END IsTopAccount
FROM A LEFT JOIN  TA 
      ON A.Area = TA.Area OR A.Name = TA.Name
ORDER BY A.Name