简体   繁体   中英

SQL using NOT EXISTS and LEFT OUTER JOIN

I have to filter some records on my primary table [Reports] for matching values in the Table Name [InsurancePlan].

In Reports, i have a column name : Code. Code has values as 1,2,3. I want to apply the below written syntax only for the Code = 1,2 and if the code = 3 , don't filter it.

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
       )

Both syntax returns the same output.

How to rewrite the query by writing the filtration for Code = 1,2

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))

Or using EXISTS operator

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

EXISTS operator is a better option when you are only checking for existance of records in a table and not returning any records from that table.

The left join option will bring all the column from InsurancePlan table if the code value is 3.

Using Exists operator will return you all the columns only from reports table if the code value is 3 and there is a corresponding record in InsurancePlan table.

Or another option to return the results from both tables will be something like

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'

Try this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM