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

时间:2017-01-30 13:18:04

标签: sql sql-server tsql

我想选择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;

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

enter image description here

2 个答案:

答案 0 :(得分:1)

如果图表要返回tblAAAtblBBB中有一行但没有一行指向tblCCC.active= 0的所有行,则:

rextester: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
          )

fp = fopen(file, "r");

while(fgets(buffer, 200, fp) != NULL )
{   
    line++; //Add new line
    if(strstr(pattern, buffer) != NULL)
    {
        sprintf(data, "%s", buffer); //So we can tell if the file is clean
        printf("Wow what do we have here?\n Data:%s\nLine:%d\n", data, line);
    }
    else if(data == NULL) 
    {
        printf("Looks like you are clean :/ or maybe i just suck\n");
    }
}

答案 1 :(得分:0)

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)
)