查找表A和表B关系中的数据

时间:2014-03-26 20:36:13

标签: sql sql-server tsql

通过查看下表,如何(写入查询)获取Table A数据和status = InActive,而Table B

中没有数据

示例: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

3 个答案:

答案 0 :(得分:1)

这很简单

select * from tableA
where status = 'InActive'
and not exists (select * from tableB where tableA.AID = tableB.AID)

答案 1 :(得分:0)

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

Szymon不存在是正确的,可能更有效

答案 2 :(得分:-1)

在这里尝试。

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