一行重复两次,我似乎无法弄清楚为什么。我试过使用Group by,但都无法弄清楚。使用左外部联接,在Northwind数据库中列出拥有打折产品的供应商
Select *
From Suppliers s
Left Outer Join products p
On s.SupplierID = p.SupplierID
Where p.Discontinued = 1
答案 0 :(得分:1)
您有两个供应商停产的产品,并且在products
中为与联接条件和Discontinued = 1
谓词相匹配的每一行创建了一行。您想要这样的东西:
SELECT * FROM Suppliers s
WHERE EXISTS (SELECT 1
FROM Products p
WHERE p.SupplierID = s.SupplierID
AND p.Discontinued = 1)
答案 1 :(得分:1)
其中一个表中有两行。您可以通过在该SupplierId上自行查询两个表来确定哪个。
现在,对您的查询,通过将p.discontinued放在where中,该连接有效地变成了内部连接,因此您应该将其翻转为内部连接,或者将该条件移至该连接。
要获得停产产品的供应商,您可以这样做:
Select * from supplier where supplierId in (
select supplierId from products
where discontinued =1)
答案 2 :(得分:1)
显然有一个供应商有多个停产的产品。
如果您希望供应商至少提供一种打折产品,请使用exists
:
select s.*
from suppliers s
where exists (select 1
from products p
where p.supplierid = s.supplierid and
p.Discontinued = 1
);
如果要提供带有停产产品数量的供应商列表,请使用join
:
select s.*, p.num_discontinued
from supplier s join
(select p.supplierid, count(*) as num_discontinued
from products
where p.Discontinued = 1
group by p.supplierid
) p
on p.SupplierID = s.SupplierID ;
如果您想要其供应商停产的产品列表,则可以使用查询,但是将left join
更改为inner join
。不需要外部联接。