请教sql高手
现在有一个表A,和另一个表B,B的parent字段保存A的ID,即B是A的子表。B有一个字段flag是布尔型的,我想将如果A对应的所有的B中所有的flag是真的时候就把A记录查询出来,怎样写sql语句?
------解决方案--------------------
create table a (id int identity(1,1), name varchar(100))
create table b (id int identity(1,1), parent int, flag bit)
insert into a select 'A'
insert into a select 'B'
insert into a select 'C'
insert into a select 'D'
insert into a select 'E'
insert into a select 'F'
insert into b select 1, 1
insert into b select 1, 1
insert into b select 1, 1
insert into b select 2, 1
insert into b select 2, 1
insert into b select 2, 0
insert into b select 3, 0
insert into b select 3, 0
insert into b select 3, 0
insert into b select 4, 1
insert into b select 4, null
insert into b select 4, null
insert into b select 5, 1
insert into b select 5, 0
insert into b select 5, null
When the table is small, use the following:
select *
from A
where exists (select * from b where B.parent = a.id)
and not exists (select * from B where A.ID=B.parent and (B.flag != 1 or B.flag is null))
When the table is large (usually over 100,000 records), use the following:
select A.*
from a
join ( select a.id
from a join b on b.parent=a.id
group by a.id
having count(*) = sum(convert(int, b.flag))
) as list
on A.id = list.id