MySQL - 限制分组依据
想象一下你有一张桌子,上面摆满了产品。每个产品都有一个价格并且属于一个特定的类别。此外,每个产品还属于一个子类别。现在,如果您想为每个子类别找到最便宜的产品怎么办?这很简单:
SELECT MIN(price), sub_category FROM products GROUP BY sub_category
对吧?
现在,假设您只想为上述结果的每个类别(而不是子类别)显示最多 2 个产品。有没有办法在 SQL 中实现这一点?
Imagine you've got a table with products. Each product has a price and belongs to a specific category. Furthermore, each product also belongs to a sub-category. Now, what if you want to find the cheapest product for each sub-category? That's easy:
SELECT MIN(price), sub_category FROM products GROUP BY sub_category
Right?
Now, imagine you only want to show a maximum of 2 products for each category (not sub-category) for the above result. Is there a way to achieve that in the SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设产品有一个唯一的 ID,您可以尝试以下操作:
编辑:@wimvds:感谢您指出错误。
编辑2:我想如果子类别中有多个具有最低价格的产品,这仍然是错误的。
Assuming the products have a unique id you may try this:
EDIT: @wimvds: Thanks for pointing out the mistake.
EDIT 2: I guess this is still wrong if there is more than one product with a minimal price in a subcategory.
不应该是这样的吗:
Shouldn't it be like this: