在MSSQL中检查master-detail中项目的状态

时间:2011-05-04 06:38:33

标签: sql sql-server tsql

我有三张桌子,即:

  • 产品
  • ProductVariant
  • SizeVariant

Product是主表,productvariant是其子表,sizevariant是productvariant的子表。

所有这些表都有状态列,表明它们是否存活。 我想检查是否有任何产品的productvariantssizevariants status已经死亡,但product本身仍然存在。

2 个答案:

答案 0 :(得分:1)

select *
from product p
where p.status = 'alive' 
  and not exists (select 1 
                  from   productvariant 
                  where  productid = p.id 
                    and  status='alive')

应该为您提供所有没有“活着”变体的产品。按照相同的公式,您还可以检查没有任何“有效”尺寸变体的产品变体:

select *
from productvariant pv
where p.status = 'alive'  
  not exists (select 1 
              from   sizevariant 
              where  productvariantid = pv.id 
                and  status='alive')

答案 1 :(得分:1)

  

是否有任何产品   productvariantssizevariants   状态已经死了,但产品本身   还活着

SELECT P1.product_ID
  FROM Products AS P1
INTERSECT
SELECT V1.product_ID
  FROM productvariants AS V1        
 WHERE V1.status = 'Dead'
INTERSECT 
SELECT V1.product_ID
  FROM productvariants AS V1        
       INNER JOIN sizevariants AS S1
         ON V1.product_variant_ID = S1.product_variant_ID
 WHERE S1.status = 'Dead';

或者(警告:可能看起来不必要地复杂):

SELECT P1.product_ID
  FROM Products AS P1
 WHERE P1.status = 'Alive'
       AND EXISTS (
                   SELECT * 
                     FROM productvariants AS V1        
                    WHERE P1.product_ID = V1.product_ID            
                          AND V1.status = 'Dead'
                  )
       AND EXISTS (
                   SELECT *
                     FROM sizevariants AS S1
                          INNER JOIN productvariants AS V1
                             ON V1.product_variant_ID = S1.product_variant_ID
                    WHERE P1.product_ID = V1.product_ID            
                          AND S1.status = 'Dead'
                  );