如果满足条件,SQL将排除结果?

时间:2012-01-06 22:15:32

标签: sql sql-server tsql

我有下表:compare。我需要使用products表进行内部联接:

idCompare idProduct dateStamp
1         1         2011-12-12
2         1         2011-12-10
3         1         2012-01-05

如果其中任何一个产品的日期在7天内,我想从我的结果中排除idproduct。

我尝试过使用NOT IN和NOT EXISTS

SELECT     products.idProduct
FROM         products INNER JOIN
             compare ON products.idProduct = compare.idProduct
WHERE
(products.idProduct = '1') AND (products.idProduct 
    NOT IN
    (SELECT     idProduct
    FROM          compare
    WHERE      (products.idProduct = compare.idProduct) AND
    (dateStamp < DATEADD(DAY, - 7, GETDATE())))) 

2 个答案:

答案 0 :(得分:2)

试试not exists

select
    *
from
    products p
    inner join compare c on
        p.idProduct = c.idProduct
where
    not exists (
        select
            1
        from
            compare c2
        where
            c2.idProduct = p.idProduct
            and c2.datestamp between dateadd(day, -7, getdate()) and getdate()
    )

答案 1 :(得分:2)

看起来像这样:

SELECT p.idProduct
FROM   products AS p
WHERE  NOT EXISTS (
   SELECT *
   FROM   compare AS c
   WHERE  c.idProduct = p.idProduct
   AND    c.dateStamp BETWEEN DATEADD(DAY, - 7, GETDATE()) AND GETDATE()
   )

另外,JOIN不要compare。根据您的说明,使用NOT EXISTS进行检查就足够了。