SQL使用NOT EXISTS和LEFT OUTER JOIN

时间:2014-03-14 16:17:44

标签: sql sql-server sql-server-2008

我必须在我的主表[Reports]上过滤一些记录,以便在表名[InsurancePlan]中匹配值。

在Reports中,我有一个列名:Code。代码的值为1,2,3。我想仅对Code = 1,2应用以下编写的语法,如果代码= 3,则不要对其进行过滤。

Select * 
  from Reports rpt
       Left join InsurancePlan Ip
           on IP.PlanName  = rpt.PlanId
 Where rpt.[Account] = 'Pharmacy'
       and Ip.PlanName is null

select * 
  from reports rpt
 where rpt.[Account] like 'Pharmacy' 
       AND NOT EXISTS(Select 1 
                        from dbo.InsurancePlan IP 
                       WHERE [rpt].[PlanId] = IP.PlanName
       )

两种语法都返回相同的输出。

如何通过编写Code = 1,2

的过滤来重写查询

2 个答案:

答案 0 :(得分:3)

Select * from  Reports rpt
Left join InsurancePlan Ip
on IP.PlanName  = rpt.PlanId
Where rpt.[Account] = 'Pharmacy'
and ((Ip.PlanName IS NULL) OR (Ip.PlanName IS NOT NULL AND rpt.Code =3))

或使用EXISTS运算符

select * 
from reports rpt
where rpt.[Account] = 'Pharmacy' 
AND rpt.Code = 3
AND EXISTS(Select 1 
           from dbo.InsurancePlan  
           WHERE [rpt].[PlanId] = PlanName
           )
当您只检查表中记录的存在而不返回该表中的任何记录时,

EXISTS运算符是更好的选项。

如果代码值为3,左连接选项将带来InsurancePlan表中的所有列。

如果代码值为3并且InsurancePlan表中有相应的记录,则使用Exists操作符将仅返回报告表中的所有列。

或者从两个表返回结果的另一个选项将类似于

Select * from  Reports rpt
Left join InsurancePlan Ip
on IP.PlanName  = rpt.PlanId AND rpt.Code =3   --<-- specify in JOIN Condition
Where rpt.[Account] = 'Pharmacy'

答案 1 :(得分:3)

试试这个:

select * from  Reports rpt
left join InsurancePlan Ip
on IP.PlanName  = rpt.PlanId
Where rpt.[Account] = 'Pharmacy'
and (rpt.Code = 3 or Ip.PlanName is null)