MySql中如何在不分组的情况下获取字段的最大值
我有一个包含许多位置和订单条件的查询。选择的字段之一是“价格”(元素价格),但我还希望(在每一行中)所有选定元素的最高价格。
我尝试在 select 上包含 MAX 聚合函数,希望这会返回所需的值,但除此之外,价格和 MAX(price) 返回相同的值。搜索MySql doc我找到了原因:
如果您在 不包含 GROUP BY 的语句 子句,相当于分组 在所有行上。
有办法解决这个问题吗?
提前致谢!
有一个类似的问题(但没有解决这个问题): find max value withoutaggregate mysql 中的运算符
I have a query with many wheres and orders criterias. One of the fields of the select is 'price' (element price) but I would like to have also (in every row) the maximun price of all the selected elements.
I tried to include MAX aggregate function on select hoping that this will return desired value, but insetead of that, price and MAX(price) returns the same. Searching into MySql doc I found the reason:
If you use a group function in a
statement containing no GROUP BY
clause, it is equivalent to grouping
on all rows.
Is there a way to solve this problem?
Thanks in advance!
There's a similar question (but not resolving this): find max value without aggregate operator in mysql
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以这样做:
我不确定为什么你想在每一行返回该值...我可能会在两个单独的查询中执行此操作,或者使用 UNION ALL:
You can do this:
I'm not sure why you'd want to return that value on every row though... I'd probably do this in two separate queries, or else use a UNION ALL:
也许你可以使用像这样的存储过程:
Maybe you could use a stored procedure like so:
我还没有尝试过这个,但是如果您有一个提取最高价格的子查询(这样您就得到一行),然后用它进行交叉连接(笛卡尔积)。你应该得到你想要的东西。我不能保证这会有多快。
I haven't tried this, but if you had a subquery that extracts the maximum price (so you get one row), and then do a cross join (cartesian product) with it. You should get something like what you want. I can't vouch for how fast this would be.