使用AdventureWorks给我一个问题,列出所有没有产品的供应商。当我运行SELECT语句时,不会返回任何内容。我究竟做错了什么? (只能使用联接和联合-无子查询来完成答案)
SELECT DISTINCT pv.Name AS 'Vendors'
FROM Purchasing.Vendor pv
INNER JOIN Purchasing.ProductVendor ppv
ON pv.BusinessEntityID = ppv.BusinessEntityID
INNER JOIN Production.Product pp
ON pp.ProductID = ppv.ProductID
WHERE pp.ProductID != ppv.ProductID;
答案 0 :(得分:2)
COUNT()
函数对产品数量进行计数。HAVING
子句请尝试以下操作:
SELECT pv.Name AS 'Vendors',
Count(pp.ProductID) AS count_products
FROM Purchasing.Vendor pv
LEFT JOIN Purchasing.ProductVendor ppv
ON pv.BusinessEntityID = ppv.BusinessEntityID
LEFT JOIN Production.Product pp
ON pp.ProductID = ppv.ProductID
GROUP BY pv.Name
HAVING count_products = 0;
答案 1 :(得分:1)
您要查看的表太多了,所有ProductVendors都有产品。并非所有供应商都有产品供应商。
您可以从那里简单地使用LEFT JOIN
并查找空记录。
SELECT DISTINCT v.Name
FROM Purchasing.Vendor v
LEFT JOIN Purchasing.ProductVendor pv ON pv.BusinessEntityID = v.BusinessEntityID
WHERE pv.BusinessEntityID IS NULL
答案 2 :(得分:-1)
SELECT DISTINCT pv.Name AS 'Vendors'
FROM Purchasing.Vendor pv
INNER JOIN Purchasing.ProductVendor ppv
ON pv.BusinessEntityID = ppv.BusinessEntityID
where not exists (SELECT 1 Production.Product pp Where pp.ProductID = ppv.ProductID)
退回所有没有任何产品的供应商