简体   繁体   中英

Finding data from Table A and Table B relation

By see below tables how to (write query) get Table A data and status = InActive with no Data in Table B

Example : 4 Comm4 InActive

Table A

AID  Name           Status
--  ---             --
1   comm1           Active
2   comm2           Active
3   Comm3           InActive
4   Comm4           InActive
5   Comm5           InActive


 Table B

 BID  Name  AID
 ---  ----  ---
  11  James 1
  12  Kris  2
  13  Dan   3
  14  Steve 3
  15  Brian 5

It's quite simple

select * from tableA
where status = 'InActive'
and not exists (select * from tableB where tableA.AID = tableB.AID)
select tableA.* 
  from tableA 
  left join tableB 
    on tableA.AID = tableB.AID 
   and tableA.status = 'InActive' 
 where tableB.AID is null 

The not exists from Szymon is correct and may be more efficient

Here you try.

select *
from #table_one
where Status = 'InActive'
and not exists
(
    select 1 from #table_two where AID = #table_one.AID
);

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