假设我有三个关系
部分(partno,partname,color)partno是P.K
供应商(supplierno,sname)supplierno是P.K
part_supplier(supplierno,partno)supplierno,partno是P.K。
现在我想得到供应部分只有一种颜色的供应商的名称。
答案 0 :(得分:1)
有条款是你的朋友。
select field1, etc, count(*) records
from yourTables
where whatever
group by field1, etc
having count(*) = 1
答案 1 :(得分:0)
Select sup.sname,count(*) from part_supplier Map
inner join supplier sup
on map.supplierno=sup.supplierno
inner join part par
on Map.partno=par.partno
group by sup.sname
having count(*)=1
答案 2 :(得分:0)
查询:
SELECT S.sname
FROM part P, supplier S, part_supplier PS
WHERE S.supplierno = ps.supplierno AND
PS.partno = P.partno
GROUP BY P.partno
HAVING count(P.color) = 1
表格:
CREATE TABLE supplier (
supplierno INT PRIMARY KEY,
suppliername VARCHAR(10) NOT NULL
);
CREATE TABLE part (
partno INT PRIMARY KEY,
partname VARCHAR(10) NOT NULL,
color INT NOT NULL
);
CREATE TABLE part_supplier (
supplierno INT NOT NULL REFERENCES supplier(supplierno),
partno INT NOT NULL REFERENCES part(partno),
PRIMARY KEY (supplierno, partno)
);
一些测试数据:
INSERT INTO part VALUES (1, 'a',1), (2, 'b',2), (3, 'c',3),
(4, 'd',1), (5, 'e',2), (6, 'c',3),
(7, 'd',1), (8, 'e',2), (9, 'e',3);
INSERT INTO supplier VALUES (1,'a'), (2,'b'), (3,'c');
INSERT INTO part_supplier VALUES (1,1), (2,1), (3,3),
(4,1), (5,1), (6,1),
(7,2), (8,2), (9,3);
答案 3 :(得分:0)
SELECT s.supplierno
FROM supplier AS s
JOIN part_supplier AS ps
ON s.supplierno = ps.supplierno
JOIN part AS p
ON ps.partno = p.partno
GROUP BY s.supplierno
HAVING COUNT(DISTINCT p.color) = 1 -- only one color for all parts