选择2列中没有特定值的记录

时间:2011-11-15 16:31:08

标签: sql sql-server

我需要选择一些在2列中没有特定值的行。目前我通过执行以下操作为单个列执行此操作:

SELECT *
FROM MyTable
WHERE    (ManufacturerID = @ManufacturerID)
    AND ItemID NOT IN(
        SELECT ItemID FROM UpdateMyTable WHERE ManufacturerID=@ManufacturerID
    )

但是现在我需要同时过滤掉不包含2个列值的行:ItemID和ChildItemID

我将如何做到这一点?

2 个答案:

答案 0 :(得分:5)

SELECT
  *
FROM
  MyTable                                 AS data
LEFT JOIN
  (SELECT x, y, z FROM UpdateMyTable)     AS check
    ON  data.x = check.x
    AND data.y = check.y
    AND data.z = check.z
WHERE
  x = @x
  AND check.x IS NULL


OR

SELECT
  *
FROM
  MyTable                                 AS data
WHERE
  x = @x
  AND NOT EXISTS (
                  SELECT
                    *
                  FROM
                    UpdateMyTable        AS check
                  WHERE
                      data.x = check.x
                  AND data.y = check.y
                  AND data.z = check.z
                 )

答案 1 :(得分:1)

您可以使用JOIN而不是NOT IN。

SELECT *
FROM MyTable t
INNER JOIN UpdateMyTable u ON t.ManufacturerId = u.ManufacturerId
WHERE t.ManufacturerId = @ManufacturerId
AND t.ItemId != u.ItemId
AND t.ItemId != u.ChildItemId