为什么我的查询忽略了一个WHERE子句?

时间:2012-09-04 09:57:24

标签: sql sql-server-2008

上午,

我无法理解为什么我的查询(下面)忽略了amzLive的WHERE子句。并且仍在返回重复项。

SELECT  asin
FROM    dbo.aboProducts
WHERE  (asin NOT IN
             (SELECT DISTINCT productAsin
              FROM   dbo.LowestPrices
              WHERE (priceDate > GETDATE() - 1))) AND (amzLive = 'true')

它返回一个项目列表,但仍然将amzLive设置为true或false的那些项目返回。

有人能看到我出错的地方吗?

更新 DB结构按要求... aboProducts表

id          int            Unchecked
asin        nvarchar(50)   Checked
codeType    int            Checked
sku         nvarchar(50)   Unchecked
amzPrice    decimal(18, 2) Checked
amzLive     bit            Checked
lastUpdated datetime       Checked

LowestPrices表

id           int            Unchecked
productAsin  nvarchar(50)   Unchecked
price        decimal(18, 2) Unchecked
postage      decimal(18, 2) Checked
priceDate    datetime       Unchecked
twAmzPrice   decimal(18, 2) Checked

3 个答案:

答案 0 :(得分:1)

这将有效

Select *
From 
(SELECT  asin,amzLive
FROM    dbo.aboProducts
WHERE  (asin NOT IN
             (SELECT DISTINCT productAsin
              FROM   dbo.LowestPrices
              WHERE (priceDate > GETDATE() - 1)
              )
         ) 
       )X
where X.amzLive = 'true'

也试试这个

SELECT ap.asin
FROM dbo.aboProducts ap
Left Join   (SELECT DISTINCT productAsin FROM dbo.LowestPrices  WHERE (priceDate > GETDATE() - 1))x
ON ap.asin  = x.productAsin
WHERE ap.amzLive = 'true' 
AND LEN(ap.asin) > 0 -- ap.asin IS NOT NULL

答案 1 :(得分:0)

SELECT  asin
FROM    dbo.aboProducts
WHERE  (asin NOT IN
             (SELECT DISTINCT productAsin
              FROM   dbo.LowestPrices
              WHERE (priceDate > dateadd(day,-1,GETDATE()) ))) AND (amzLive = 'true')

答案 2 :(得分:0)

  1. 不要对位使用'true'和'false',使用1或0
  2. left join会让您的查询更清晰,更可预测
  3. 仅供参考,SQL Server有货币数据类型
  4. 例如

    select ASIN
    from aboProducts
        left join lowestprices
            on aboProducts.asin = lowestprices.productAsin
            and lowestprices.pricedate > (GETDATE()-1)
    where lowestprices.productAsin is null
    and aboProducts.amzlive=1