我有一个SQL Server 2008数据库。该数据库有两个相关的表:Customer和Order。我的表看起来像这样:
Customer
--------
ID
FirstName
LastName
Order
-----
ID
CustomerID
Amount
ShipDate
我需要删除所有没有订单的客户。我无法弄清楚这样做的最佳方法。谁能告诉我怎么做? NOT部分是让我不断的。最初我使用的是“IN”,但这让我很难过。
感谢您的帮助!
答案 0 :(得分:2)
使用子查询和NOT
EXISTS
,而不是使用IN运算符,如:
DELETE Customers
FROM Customers c
WHERE NOT EXISTS (
SELECT 1
FROM Orders o
WHERE o.CustomerID = c.ID
)
答案 1 :(得分:0)
DELETE Customer
WHERE ID IN
(
SELECT Customer.ID
FROM Customer
LEFT JOIN Order ON
Customer.ID = ORder.CustomerID
WHERE ORder.CustomerID IS NULL
)
答案 2 :(得分:0)
Delete from Customer
WHERE ID in
(
SELECT C.ID
FROM Customer C
Left Outer Join Order O ON C.ID = O.CustomerId
WHERE O.ID IS NULL
)