繁体   English   中英

选择具有一对多条件的所有行

[英]Select all rows with one-to-many condition

我想选择 tblAAA 中满足条件的所有行。

一个 tblAAA 有 1 个或多个 tblBBB。 一个 tblBBB 有 1 个 tblCCC。 我想更新 tblAAA 中的所有行,其中所有tblBBB 都有一个 tblCCC,其中 tblCCC.status = 1。

请参阅提供的图像。

真的很棒的帮助,我一直盯着这个两个小时,但不知道。

编辑:我尝试过的一件事是:

select * from tblAAA
inner join tblBBB
on tblAAA.tblAAA_id = tblBBB.tblAAA_id
inner join tblCCC
on tblBBB.tblCCC_id = tblCCC.tblCCC_id
where tblCCC.status = 1;

但这不起作用,因为这给出了至少一个 tblBBB 满足条件的所有 tblAAA。

在此处输入图片说明

如果图是说返回所有行tblAAA有一排tblBBB ,但没有一排导致tblCCC.active= 0 ,则:

雷克斯特: http: //rextester.com/OBOE63409

create table tblAAA (AAA_Id int, status bit);
insert into tblAAA values (1,1),(2,0),(3,1);

create table tblBBB (BBB_id int identity(1,1), AAA_id int, CCC_id int);
insert into tblBBB values (1,1),(2,1),(2,2);

create table tblCCC (CCC_id int, active bit);
insert into tblCCC values (1,1),(2,0);

/* AAA_Id 1 has only one row in tblBBB and leads to tblCCC.active=1 */
/* AAA_Id 2 has only two rows in tblBBB and one leads to tblCCC.active=0 */
/* AAA_Id 3 has no row in tblBBB -- not returned */

/* using the inner join from tblAAA to tblBBB 
  requires that AAA_id have at least one row in tblBBB */

select a.AAA_id, a.status
  from tblAAA as a
    inner join tblBBB as b on a.AAA_id = b.AAA_id
  where not exists (
    select 1
      from tblBBB as b
        inner join tblCCC as c on b.CCC_id=c.CCC_id
        where b.AAA_id = a.AAA_ID
          and c.active=0
  )
  group by a.AAA_id, a.status
  /* if AAA_id must have at least n rows in tblBBB 
     that lead to tblCCC.active=1
     then using having count(b.Id) > n */
  --having count(b.Id)>1

更新所有tblAAA ,其中所有tblBBB都有一个tblCCC ,其中tblCCC.active = 1

update a
  set a.status=1
  from tblAAA as a
    inner join tblBBB as b on a.AAA_id = b.AAA_id
  where not exists (
    select 1
      from tblBBB as b
        inner join tblCCC as c on b.CCC_id=c.CCC_id
        where b.AAA_id = a.AAA_ID
          and c.active=0
    )

或者

update a
  set a.status=1
  from tblAAA as a
  where not exists (
    select 1
      from tblBBB as b
        inner join tblCCC as c on b.CCC_id=c.CCC_id
        where b.AAA_id = a.AAA_ID
          and c.active=0
    )
    and exists (
      select 1
        from tblBBB as b
          where b.AAA_id = a.AAA_ID
          )
update tblAAA
set status = 'new status'
where AAA_ID in (
    select a.AAA_ID
    from tblAAA a
    join tblBBB b on a.AAA_ID = b.AAA_ID
    join tblCCC c on c.CCC_ID = b.CCC_ID
    group by a.AAA_ID, a.status
    having sum(case c.active when 1 then 1 else 0 end) = count(c.active)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM