MySQL 左连接 +最小
看似简单的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
我如何返回该最低价格的相应prices.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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 Items 中的一条记录有多个具有最低价格的 Price 记录,则将返回该记录的多个记录:
This will return multiple records for a record in Items if there are multiple Prices records for it with the minimum price:
新的有效答案,基于 MySQL 5.0 参考手册中的最后一个示例 - 3.6.4.持有特定列的分组最大值的行:
LEFT JOIN
的工作原理是,当prices.price
处于最小值时,有不存在具有较小值的filter.price
,并且filter
行值将为 NULL。原错误答案:
New, working answer, based on the final example in the MySQL 5.0 Reference Manual - 3.6.4. The Rows Holding the Group-wise Maximum of a Certain Column:
The
LEFT JOIN
works on the basis that whenprices.price
is at its minimum value, there is nofilter.price
with a smaller value and thefilter
rows values will be NULL.Original incorrect answer:
好吧,怎么样?
Ok, how about?