MySQL按ID分组和按MIN订购(价格)

时间:2014-01-26 19:52:36

标签: php mysql group-by sql-order-by min

好的,所以我遵循MySQL声明......

目标是通过“id”代码将所有产品“库存”分组,并显示“最低价格”的产品。

我原本以为只通过id进行分组,在ORDER BY子句中添加MIN(price)可以完成这项工作,但显然不是......

SELECT *  
FROM (`products`)  
WHERE `in_stock` = 'yes'  
GROUP BY `id`  
ORDER BY brand, line, product, size, unit, MIN(price)  
LIMIT 25

有人可以帮忙吗?

示例数据:

id  brand   line        product size    unit    price   url
123 Adidas  Deep Energy EDT 50  ml  10.00   Link1
123 Adidas  Deep Energy EDT 50  ml  8.75    Link2
123 Adidas  Deep Energy EDT 50  ml  9.99    Link3
124 Adidas  Deep Energy EDT 100 ml  15.00   Link4

所以,实际上我试图放在一起的查询会返回上面示例数据的第2行和第4行(“123”和“124”的最低价格行)

1 个答案:

答案 0 :(得分:0)

您将最低价格计算为:

SELECT id, MIN(price)   
FROM products
WHERE in_stock = 'yes'  
GROUP BY id ; 

要获得价格最低的行,您需要将其加入:

select p.*
from products p join
     (SELECT id, MIN(price) as minprice  
      FROM products
      WHERE in_stock = 'yes'  
      GROUP BY id 
     ) pmin
     on p.id = pmin.id and p.price = pmin.minprice;