SQL:帮助嵌套查询

时间:2010-02-21 04:22:18

标签: sql mysql declarative nested-query

这是我的架构:

供应商( sid:整数,sname:字符串,地址字符串)

零件( pid:整数, pname:string,color:string)

目录( sid:整数,pid:整数,成本:真实)

粗体表示主键。

我想写一个查询来查找供应每个部分的所有供应商。以下是我已经提出的两个问题:

-- 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

在命令性的条件下,我想要做的是这样的事情:

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

如何将其转换为MySQL?

4 个答案:

答案 0 :(得分:0)

不确定它是如何转换为MySQL的,但也是如此:

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)

注意标记子查询“a”是一个任意名称,因为MSSQL由于某种原因需要在其子查询中使用名称。不知道它在MySQL中是如何工作的。

答案 1 :(得分:0)

尝试(未经测试):

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)

答案 2 :(得分:0)

尝试:

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)

答案 3 :(得分:0)

使用:

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