我对此非常陌生,所以我会尽力解释这个问题,尽量解释一下,谢谢!
我有一张公司在购买东西时获得的账单清单,我只想选择那些没有购买任何东西的账单(因此他们的客户ID不在账单上)。我该怎么做?
到目前为止,这是我的代码(将某些内容重命名为英语,以便您希望更好地理解):
SELECT Name, Postnr+' '+City as Postadress
FROM Bill
RIGHT JOIN Customer
ON Customer.CustomerID = Bill.CustomerID
答案 0 :(得分:1)
同时我更喜欢NOT EXISTS
,因为它更易读,可维护并且没有空值问题:
SELECT Name,
Postnr + ' ' + City AS Postadress
FROM Customer c
WHERE NOT EXISTS (SELECT 1 FROM bill b
WHERE b.CustomerID = c.CustomerID)
另一种(可能效率较低)方式是OUTER JOIN
:
SELECT Name,
Postnr + ' ' + City AS Postadress
FROM Customer c
LEFT OUTER JOIN Bill b
ON c.CustomerID = b.CustomerID
WHERE b.CustomerID IS NULL
以下列出了所有方法:
Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
答案 1 :(得分:0)
你解释得很清楚。你应该从你的解释中做出正确的SQL: 客户的客户ID不在账单清单中。现在这就像:
select * from Customer where CustomerID not in (select CustomerID from Bill)
取决于您的数据库系统,语法可能略有不同,例如不是...中的CustomerID
答案 2 :(得分:0)
SELECT Name, Postnr+' '+City as Postadress
FROM Bill
RIGHT JOIN Customer
ON Customer.CustomerID = Bill.CustomerID
WHERE Customer.CustomerID NOT IN (SELECT Bill.CustomerID FROM Bill)