Here is my schema:
Suppliers(sid: integer, sname: string, address string)
Parts(pid: integer, pname: string, color: string)
Catalog(sid: integer, pid: integer, cost: real)
Primary keys in bold.
Here is the MySQL query I'm working with:
-- Find the sids of suppliers who supply every red part or supply every green part.
-- this isn't DRY
-- not tested
SELECT Suppliers.sid
FROM Suppliers
JOIN (SELECT sid, COUNT(Parts.pid) AS partsPerSupplier
FROM Catalog
JOIN Parts on Catalog.pid = Parts.pid
WHERE Parts.color = "red"
GROUP BY sid)
AS partCounts ON Suppliers.sid = partCounts.sid
JOIN (SELECT COUNT(pid) AS totalParts
FROM Parts
WHERE color = "red"
) AS totalPartsTable ON totalPartsTable.totalParts = partCounts.partsPerSupplier
UNION
SELECT Suppliers.sid
FROM Suppliers
JOIN (SELECT sid, COUNT(Parts.pid) AS partsPerSupplier
FROM Catalog
JOIN Parts on Catalog.pid = Parts.pid
WHERE Parts.color = "green"
GROUP BY sid)
AS partCounts ON Suppliers.sid = partCounts.sid
JOIN (SELECT COUNT(pid) AS totalParts
FROM Parts
WHERE color = "green"
) AS totalPartsTable ON totalPartsTable.totalParts = partCounts.partsPerSupplier;
The subqueries on either side of the UNION
statement are hideously repeated. In imperative programming, this would be a good place to make a function, taking the color as a parameter. What is the equivalent of this in MySQL?
I have heard of "views" but I think that might be overkill for this case.