SQL: Help with a nested queries
-
21-09-2019 - |
Question
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)
bold indicates primary key.
I want to write a query to find all suppliers who supply every part. Here are two queries I have already:
-- get all parts for a given supplier
SELECT Parts.pid
FROM Suppliers
JOIN Catalog ON Catalog.sid = Suppliers.sid
JOIN Parts ON Parts.pid = Catalog.pid
WHERE Suppliers.sid = 4;
-- gets all parts that exist
SELECT Parts.pid
FROM Parts
What I want to do, in imperative terms, is something like this:
Define result set
Foreach Supplier:
If the list of parts produced by a supplier
is equal to the total list of parts, add this supplier to the result set
Return result set
How can I translate this into MySQL?
Solution
Use:
SELECT s.*
FROM SUPPLIER s
JOIN (SELECT c.sid,
COUNT(c.pid) AS num_parts
FROM CATALOG c
GROUP BY c.sid) x ON x.sid = s.sid
JOIN (SELECT COUNT(*) AS total_parts
FROM PARTS) y ON y.total_parts = x.num_parts
OTHER TIPS
Not sure how it translates to MySQL, but something along these lines:
select s.sname, PartCount from (
select s.SID, s.sname, PartCount = sum(p.PID)
inner join Catalog c on c.SID = s.SID
inner join Parts p on p.PID = c.PID
where s.SID = 4
group by s.SID
) a
where PartCount = MAX(PartCount)
Note labeling the subquery 'a' is an arbitrary name as MSSQL requires names on its subqueries for some reason. Dunno how it works in MySQL.
Try (untested):
SELECT s.*
FROM (
SELECT sid, count(pid) as c
FROM Catalog
GROUP BY sid) q1
JOIN Suppliers s ON s.sid = q1.sid
WHERE q1.c = (SELECT COUNT(*) FROM Parts)
Try:
SELECT Suppliers.sid
FROM Suppliers
INNER JOIN
(SELECT sid, COUNT(pid) as num
FROM Catalog
GROUP BY sid)as t1
ON Suppliers.sid = t1.sid
WHERE t1.num =
(SELECT COUNT(pid) FROM Parts)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow