我坚持下一步该做什么。我需要撰写一个查询,告诉我位于特定城市的供应商是否都提供了共同的部分。我创建了以下查询
select sh1.partno,sh1.supplierno
from shipments sh1
where sh1.supplierno IN (
select s.supplierno
from suppliers s
where s.city = 'LONDON')
返回
partno supplierno
P1 S1
P1 S1
P3 S1
P3 S1
P3 S1
P6 S4
P2 S4
P5 S4
P5 S4
我坚持下一步该做什么。以下是指定城市供应商发运的所有零件。如何比较这两列,以便您想知道一个公共部件号是否由supplierno列中列出的两个不同供应商编号附带。我知道这不会有结果,但我仍然需要知道如何前进。
提前致谢
答案 0 :(得分:1)
自我加入可能就是你想要的。
select yourfields
from shipments sh1 join shipments sh2 on sh1.partno = sh2.partno
and sh1.supplierid <> sh2.supplierid
etc
修改强>
没有连接关键字的相同查询
select yourfields
from shipments sh1, shipments sh2
where sh1.partno = sh2.partno
and sh1.supplierid <> sh2.supplierid
etc
答案 1 :(得分:0)
如果您从供应商和零件的基本列表(按城市过滤)开始,您的初始查询将是:
SELECT sh1.partno,sh1.supplierno
FROM
shipments sh1
INNER JOIN
suppliers s ON
sh1.supplierno = s.supplierno
WHERE s.city = 'LONDON'
这将为您提供供应商和零件的清单。不能使用JOIN而不是限制你 - 我不会真正考虑一个适当过滤的自我加入笛卡尔产品,但是,嘿,这是他的班级。
如果需要,可以使用GROUP BY和HAVING子句获取部件列表,例如:
SELECT sh1.partno, COUNT(DISTINCT sh1.supplierno) AS NumberOfSuppliers
FROM
shipments sh1
INNER JOIN
suppliers s ON
sh1.supplierno = s.supplierno
WHERE s.city = 'LONDON'
GROUP BY sh1.partno
HAVING MIN(sh1.supplierno) <> MAX(sh1.supplierno)
另一方面,如果您正在寻找零件和供应商,则需要将供应商清单条款与另一个供应商和零件清单相结合。 JOIN是最有意义的,但是如果那个禁止EXISTS关键字可以帮助你 - 这样的事情可能会让你想要的东西(如果你想要的话,那就不记得了)这是对的,所以请告诉我它是否有效。
SELECT sh1.partno, sh1.supplierno
FROM
shipments sh1
INNER JOIN
suppliers s ON
sh1.supplierno = s.supplierno
WHERE
s.city = 'LONDON' AND
EXISTS
(
SELECT sh2.supplierno
FROM
shipments sh2
INNER JOIN
suppliers s2 ON
sh2.supplierno = s2.supplierno
WHERE
s2.City = 'LONDON' AND
sh2.supplierno != sh1.supplierno AND
sh2.partno = sh1.partno
)
然而,我会推荐@Dan Bracuk提出的关于其中任何一个的自我加入。
答案 2 :(得分:0)
伦敦的供应商数量:
select count(distinct s.supplierno)
from suppliers s
where s.city = 'LONDON'
伦敦每个零件供应商的数量:
select sh1.partno, count(distinct sh1.supplierno)
from shipments sh1
where sh1.supplierno IN (
select s.supplierno
from suppliers s
where s.city = 'LONDON'
)
group by sh1.partno
哪个部分在伦敦拥有的供应商与伦敦的供应商一样多?提示,将简化剩下的内容