简体   繁体   中英

sql join issue, not able to retrieve records from table a which matches some condition in table b and remaining left out table a records

I am writing a sql query to get all those records from table A which matches table b with certain condition, and all left out records from table a , which are not there in table b. Below is the code and tables

Table A

skey    OrderName    
100     Pen     
100     Cutter  
101     any     

Table b

skey    OrderName   Key
100     Pen        True
100     Cutter      



select a.skey,a.orderName
from Test_A a
     left join Test_B b
     on a.skey=b.skey
where b.kit='True' and a.orderName=b.orderName

Result I need is

skey   Ordername  
100       Pen (Because this is true in table B)
101       any 

Here is the idea:

select a.skey, a.orderName
from Test_A a left join
     Test_B b
     on a.skey = b.skey and
        a.orderName = b.orderName 
where b.kit = 'True' or   -- matches and value is true
      b.skey is null.     -- no match

You can try the below -

select a.skey,a.orderName from Test_A a
left join Test_B b
on a.skey=b.skey  and a.orderName=b.orderName
where b.kit='True' and b.skey is null

You can use NOT EXISTS in the WHERE clause like this:

SELECT a.* 
FROM Test_A a LEFT JOIN Test_B b
ON b.skey = a.skey AND b.OrderName = a.OrderName 
WHERE b.kit = 'True'
   OR (b.kit IS NULL AND NOT EXISTS (SELECT 1 FROM Test_B WHERE skey = a.skey AND kit = 'True'))

Or without a join:

SELECT a.* 
FROM Test_A a 
WHERE EXISTS (SELECT 1 FROM Test_B b WHERE b.skey = a.skey AND b.OrderName = a.OrderName AND b.kit = 'True') 
OR NOT EXISTS (SELECT 1 FROM Test_B b WHERE b.skey = a.skey AND b.kit = 'True')

See the demo .
Results:

> skey | OrderName
> ---: | :--------
>  100 | Pen      
>  101 | any      

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