MySQL Left Join + Min

时间:2011-09-28 18:58:21

标签: mysql group-by left-join greatest-n-per-group min

看似简单的MySQL问题,但我从来没有这么做过..

我有两张桌子,物品和价格,有一对多的关系。

Items Table
id, name

Prices Table
id, item_id, price

其中

prices.item_id = items.id

到目前为止我所拥有的:

SELECT items.id, items.name, MIN(prices.price)
FROM items
LEFT JOIN prices ON items.id = prices.item_id
GROUP BY items.id

如何以最低价格返回相应的price.id?谢谢!

4 个答案:

答案 0 :(得分:24)

如果有最多价格的多个价格记录,这将为Items中的记录返回多条记录:

select items.id, items.name, prices.price, prices.id
from items
left join prices on (
    items.id = prices.item_id 
    and prices.price = (
        select min(price)
        from prices
        where item_id = items.id
    )
);

答案 1 :(得分:11)

基于MySQL 5.0参考手册中的最后一个示例 - 3.6.4. The Rows Holding the Group-wise Maximum of a Certain Column的新工作答案:

SELECT items.id, items.name, prices.price, prices.id
FROM items 
LEFT JOIN prices
    ON prices.item_id = items.id
LEFT JOIN prices AS filter
    ON filter.item_id = prices.item_id
    AND filter.price < prices.price
WHERE filter.id IS NULL

LEFT JOIN的工作原理是,当prices.price处于最小值时,没有filter.price值较小且filter行值为NULL


原始错误答案:

SELECT items.id, items.name, prices.price, prices.id
FROM items 
LEFT JOIN prices ON prices.item_id = items.id
ORDER BY prices.price ASC
LIMIT 1

答案 2 :(得分:0)

好的,怎么样?

SELECT items.id, items.name, MIN(prices.price), prices.id
FROM items 
LEFT JOIN prices ON items.id = prices.item_id 
GROUP BY items.id, MIN(prices.price)  

答案 3 :(得分:0)

SELECT top 1 items.id, items.name, prices.price, prices.id 
FROM items  
LEFT JOIN prices ON items.id = prices.item_id  
ORDER BY prices.price ASC