删除所有找不到JOIN的行?

时间:2011-05-24 16:45:29

标签: sql sql-server select inner-join

我有这个问题:

SELECT Auctions.ID 
FROM Auctions
INNER JOIN Products ON Auctions.ProductID = Products.ID

据我所知,如果我有拍卖会:

ID | ProductID
1  |   12

ProductID 12不在Products表中,因此不会选择该行。

如果我是对的,我想删除在Products表上找不到产品ID的所有行。 (无法找到JOIN的产品)

我该怎么做?

4 个答案:

答案 0 :(得分:5)

DELETE FROM a
    FROM Auctions a
    WHERE NOT EXISTS(SELECT NULL FROM Products p WHERE p.ID = a.ProductID)

答案 1 :(得分:4)

DELETE Auctions WHERE ProductId NOT IN(SELECT ProductId FROM Products)

当然,执行此操作后,如果您不想再次执行此操作,请自行帮助并创建从Auctions.ProductIdProducts.ProductId的关系。

答案 2 :(得分:3)

对上述答案略有不同。第一个显示拍卖没有相应的产品,第二个实际清除它们。如果存在缺失产品的模式,首先可能会有所帮助。

-- This query identifies everything that is in
-- Auctions that doesn't have a match in Product
SELECT
    A.*
FROM
    Auctions A
    LEFT OUTER JOIN 
        Products P 
        ON A.ProductID = P.ID
WHERE
    P.ProductID IS NULL


-- This query deletes everything that is in
-- Auctions that doesn't have a match in Product
DELETE
    A
FROM
    Auctions A
    LEFT OUTER JOIN 
        Products P 
        ON A.ProductID = P.ID
WHERE
    P.ProductID IS NULL

答案 3 :(得分:2)

DELETE FROM Auctions WHERE ProductId NOT IN (SELECT ProductId FROM Products)