日期:2014-05-18 浏览次数:20416 次
TableA ID name 1 刘 2 王 3 李 4 吴 5 陈 TableB ID No Comment 1 1 AB 1 2 AA 1 5 AD 2 3 AG 2 6 AF 3 5 DD 4 1 MM 4 5 KL
select a.* from table a join (select id from tableb where no in(1,5) having count(distinct no)=2) b on a.id=b.id
------解决方案--------------------
create table TableA(ID int,name varchar(10)) insert into tablea values(1 , '刘') insert into tablea values(2 , '王') insert into tablea values(3 , '李') insert into tablea values(4 , '吴') insert into tablea values(5 , '陈') create table TableB(ID int,No int,Comment varchar(10)) insert into tableb values(1 , 1 , 'AB') insert into tableb values(1 , 2 , 'AA') insert into tableb values(1 , 5 , 'AD') insert into tableb values(2 , 3 , 'AG') insert into tableb values(2 , 6 , 'AF') insert into tableb values(3 , 5 , 'DD') insert into tableb values(4 , 1 , 'MM') insert into tableb values(4 , 5 , 'KL') go select a.* from tablea a , ( select distinct id from tableb where no = 1 union all select distinct id from tableb where no = 5 ) b where a.id = b.id and b.id not in (select id from tableb where no not in (1,5)) group by a.id , a.name having count(1) = 2 drop table tablea , tableb /* ID name ----------- ---------- 4 吴 (所影响的行数为 1 行) */
------解决方案--------------------
go
create table #a(
ID int,
name varchar(2)
)
go
insert #a
select 1,'刘' union all
select 2,'王' union all
select 3,'李' union all
select 4,'吴' union all
select 5,'陈'
go
create table #b(
ID int,
Num int,
Comment varchar(2)
)
go
insert #b
select 1,1,'AB' union all
select 1,2,'AA' union all
select 1,5,'AD' union all
select 2,3,'AG' union all
select 2,6,'AF' union all
select 3,5,'DD' union all
select 4,1,'MM' union all
select 4,5,'KL'
select * from #a where ID in
(select ID from
(select distinct ID from #b where Num = 1
union all
select distinct ID from #b where Num = 5)t
where ID not in (select ID from #b where Num not in (1,5))
group by ID having count(1)=2)