Select table MySQL 中的最低值

Select lowest value within a table MySQL

我想从以下table中的最低价得到id_product_attribute

id_product | id_product_attribute  | price
210        | 131                   | 44.950000
210        | 132                   | 39.550000
210        | 134                   | 22.820000
210        | *135                  | 18.250000
211        | 137                   | 36.230000
211        | *138                  | 28.980000

我得到的最接近的是这个查询:

SELECT
    id_product,id_product_attribute,MIN(price) as price
FROM product_attribute 
WHERE price IN(
        SELECT MIN(price) 
        FROM product_attribute 
        GROUP BY id_product)
GROUP BY id_product

虽然成功获得了最低值(这里问过我的时间),但它 return 不正确 id_product_attribute。我在子查询中尝试了一些 ORDER BY,但这对我也不起作用。

提前致谢!

你的子查询需要 select min(price) AND id_product,因为这是两个字段,你必须加入派生的table,因为您将无法再使用 in() 匹配项:

SELECT *
FROM product_attribute AS pa
LEFT JOIN (
    SELECT id_product, MIN(price) as price
    FROM product_attribute
    GROUP BY id_product
) AS minprices
   ON pa.id_product = minprices.id_product 
       AND pa.price = minprices.price