在where子句中使用标志的不同外键值的不同结果

时间:2010-06-04 13:36:46

标签: sql sql-server-2005

请参阅附图。

alt text http://img241.imageshack.us/img241/3585/customcost.png

请告诉我哪些查询有效。请忽略isdefinite和productpriceid列。

由于

2 个答案:

答案 0 :(得分:0)

如果你想要一个查询,如果我已正确解释你的问题,这应该这样做:

SELECT  DISTINCT t1.SupplierVenueProductID, [...]
FROM    table t1
        LEFT JOIN
                table t2
                ON t1.SupplierVenueProductID = t2.SupplierVenueProductID
                AND t2.iscustomcost = 1
WHERE   t2.SupplierVenueProductID IS NULL
OR      t1.iscustomcost = 1

我不知道你的表名,但你加入了它自己。

答案 1 :(得分:0)

我对你想要在这里完成的事情有点失落, 根据您的要求如果isCustomCost = 1,则返回SupplierVenueProductId 1中的记录#3和来自SupplierVenueProductId 2的两条记录

试图概括一下,我认为你需要的是

返回表中的所有行,除非有一个具有isCustomCost = 1的SupplierVenueProductId的记录,那么只返回该SupplierVenueProductId 的记录

然后它变成了以下内容:

SELECT t1.* 
  FROM myTable t1
 WHERE t1.isCustomCost = 1
    OR NOT EXISTs (SELECT *
                     FROM t2
                    WHERE t2.SupplierVenueProductId = t1.SupplierVenueProductId
                      AND t2.isCustomCost = 1)

希望这有帮助。