SQL查询查找每个部件价格最低的供应商

时间:2017-02-24 19:15:57

标签: mysql sql

我需要找到每个零件价格最低的供应商。

表:供应商(sid,sname,地址),部件(pid,pname,颜色),目录(sid,pid,cost)

这有效:

SELECT 
    sname, pid
FROM
    (SELECT 
        *
    FROM
        suppliers
    NATURAL JOIN catalog
    NATURAL JOIN (SELECT 
        pid, MIN(cost) AS min_cost
    FROM
        catalog
    GROUP BY (pid)) AS m
    HAVING cost = min_cost) AS n

但是当我尝试将其缩短到以下内容时,我得到一个错误,即在having子句中存在未知成本:

SELECT 
    sname, pid
FROM
    suppliers
        NATURAL JOIN
    catalog
        NATURAL JOIN
    (SELECT 
        pid, MIN(cost) AS min_cost
    FROM
        catalog
    GROUP BY (pid)) AS m
HAVING cost = min_cost

为什么不能找到成本?表格中的成本是不是因为我已经将子查询加入了目录?

修改

根据建议,我将其更改为使用INNER JOIN而不是NATURAL JOIN,但我仍然遇到同样的错误。新查询:

SELECT 
    s.sname, m.pid
FROM
    suppliers s
        INNER JOIN
    catalog c ON s.sid = c.sid
        INNER JOIN
    (SELECT 
        pid, MIN(cost) AS min_cost
    FROM
        catalog
    GROUP BY (pid)) AS m ON c.pid = m.pid
HAVING cost = min_cost

EDIT_2

问题不是JOIN,而是HAVING,实际应该是WHERE,如bbrumm的回答所示。

1 个答案:

答案 0 :(得分:4)

我建议像这样的查询:

SELECT
supplier.sname,
catalog.pid
FROM suppliers
INNER JOIN catalog ON suppliers.supplier_id = catalog.supplier_id 
INNER JOIN 
    (SELECT 
     pid, MIN(cost) AS min_cost
    FROM catalog
    GROUP BY (pid)) AS m
ON catalog.pid = m.pid
WHERE catalog.cost = m.min_cost;

我对您可能需要更改的列名(例如supplier_id)做了一些假设。可以说“cost = min_cost”是JOIN的一部分,所以它也可以去那里。我也没有包括表别名,因为它是最好的做法,它不是必需的。