本文介绍了MySQL左连接+最小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来很简单的MySQL问题,但我从来没有这样做过。我有两个表格,项目和价格,很多关系。
物品表
id,名称
物品表
id,item_id ,价格
其中
prices.item_id = items.id
到目前为止: p>
SELECT items.id,items.name,MIN(prices.price)
FROM items
LEFT JOIN价格ON items.id = prices.item_id
GROUP BY items.id
我怎么也为最低价格返回相应的price.id?感谢!
解决方案
如果以最低价格存在多个价格记录,这将返回Items中记录的多个记录:
select items.id,items.name,prices.price,prices.id
from items
(
items.id = prices.item_id
和prices.price =(
)从价格
中选择min(price)
where item_id = items。 id
)
);
Seemingly simple MySQL question, but I've never had to do this before..
I have two tables, items and prices, with a one-to-many relationship.
Items Table
id, name
Prices Table
id, item_id, price
Where
prices.item_id = items.id
What I have so far:
SELECT items.id, items.name, MIN(prices.price)
FROM items
LEFT JOIN prices ON items.id = prices.item_id
GROUP BY items.id
How do I also return the corresponding prices.id for that minimum price? Thanks!
解决方案
This will return multiple records for a record in Items if there are multiple Prices records for it with the minimum price:
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
)
);
这篇关于MySQL左连接+最小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!