我在 MySQL 中有以下关系:
Suppliers(**sid**; sname; city),
Parts(**pid**; pname; color),
Catalog(**sid**; **pid**; cost),
键在 *.
我想找到:
- 供应商对 (s1; s2) 使得 s1 和 s2 提供完全相同的零件。
- 提供至少两个其他人不提供的零件的供应商。
非常感谢您的回复。我自己写了以下查询,但我不确定它是否正确。请告诉我。谢谢。
1)
选择 T1.sid,T2.sid
从 T1、T2
哪里(选择 T1.sid,C2.pid
FROM( SELECT c1.pid
FROM Catalog C1
GROUP BY c1.sid) AS T1, Catalog C2
WHERE T1.sid=c2.sid)
=
(SELECT T2.sid, C4.pid
FROM( SELECT c3.pid
FROM Catalog C3
GROUP BY c3.sid) AS T2, Catalog C4
WHERE T2.sid=c4.sid)
2)
选择 T1.S
从 T1
WHERE NOT EXISTS(( SELECT c1.sid AS S, c1.pid AS p1, C2.pid AS p2
FROM catalog AS C1, Catalog as C2
WHERE c1.sid=c2.sid AND
C1.pid<>c2.pid) AS T1
EXCEPT
( SELECT c3.sid AS S1, c3.pid AS p3, C4.pid AS p4
FROM catalog AS C3, Catalog as C4
WHERE c3.sid=c4.sid AND
c3.pid<>c4.pid) AS T2)
不存在((选择 c3.sid 作为 S1,c3.pid 作为 p3,C4.pid 作为 p4
FROM catalog AS C3, Catalog as C4
WHERE c3.sid=c4.sid AND
c3.pid<>c4.pid) AS T2)
EXCEPT
(SELECT c1.sid AS S, c1.pid AS p1, C2.pid AS p2
FROM catalog AS C1, Catalog as C2
WHERE c1.sid=c2.sid AND
C1.pid<>c2.pid) AS T1
1. 供应商对 (s1; s2) 使得 s1 和 s2 供应完全相同的零件:
select c1.sid,c2.sid
from catalog c1 join catalog c2 on c1.pid = c2.pid and c1.sid < c2.sid
and not exists
(
select 1
from catalog c3 join catalog c4
on c3.sid = c1.id and c4.id = c2.sid
and c3.pid <> c4.pid
)
2.供应商至少提供两个其他人不提供的零件。
select c1.sid
from catalog c1 join catalog c2 on c1.sid = c2.sid and c1.pid < c2.pid
and not exists
(
select 1
from catalog
where sid <> c1.sid and (pid = c1.pid or pid = c2.pid)
)
SELECT supplier_1, supplier_2
FROM ( SELECT c.sid AS supplier_1, c2.sid AS supplier 2, COUNT(*) AS total, COUNT(c2.sid) AS connected
FROM Catalog AS c
LEFT JOIN Catalog AS c2
ON c.sid != c2.sid AND c.pid = c2.pid
GROUP BY c.sid, c2.sid) AS h
GROUP BY LEAST(supplier_1, supplier_2), GREATEST(supplier_1, supplier_2)
我想像这样的事情会成功。基本上只是LEFT JOIN
根据不等于同一个供应商和相等的部分id做一个,然后看看连接的数量是否等于没有成功连接的行数。