如何查询具有最低值的行,又如何知道最高值的值?

编程入门 行业动态 更新时间:2024-10-24 18:20:19
本文介绍了如何查询具有最低值的行,又如何知道最高值的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑以下两个查询:

SELECT *, 'b' AS b FROM someTable ORDER BY a ASC LIMIT 1; SELECT *, MAX(a) AS maxA FROM someTable ORDER BY a ASC LIMIT 1;

如前所述,前一个查询返回具有最低值a的行.后一个查询返回存储在磁盘上的第一行(通常是主键值最低的行). 我该如何解决?我的目的是获得具有最低a值的列的整行(如果有多个,我只需要一个即可,这无关紧要) ,此外,我确实需要最高年龄的价值观.在理想情况下,我将运行两个查询,但是由于对象在此应用程序中的序列化方式,如果不重构很多不是我的代码,我将无法做到这一点.我实际上不介意MySQL引擎本身是否必须查询两次,重要的一点是输出必须在一行中返回.不幸的是,我无法为此查询编写存储过程.是的,*运算符很重要,我无法列出所需的字段.而且有太多的行无法全部归还!

The former query returns the row with the lowest value of a, as expected. The latter query returns the first row stored on disk (usually the row with the lowest value for primary key). How can I work around this? My intention is to get the full row of the column with the lowest a value (if there is more than one I only need one, it does not matter which), and additionally I do need the value of the highest age. In a perfect world I would run two queries, but due to the way that objects are serialised in this application I cannot do that without refactoring a lot of code that isn't mine. I actually don't mind if the MySQL engine itself must query twice, the important bit is that the output be returned in a single row. I cannot write a stored procedure for this query, unfortunately. And yes, the * operator is important, I cannot list the needed fields. And there are too many row to return them all!

请注意,此问题与先前的问题,但是该问题的存在形式不明确,模棱两可,因此所有答案都解决了我不是故意的问题(但是,我确实学过很多,我很高兴原来如此.)这个问题更清楚地问了预期的问题,因此应该吸引不同的答案.

Note that this question is superficially similar to a previous question, however the question asked there was ill-formed and ambiguous, therefore all the answers addressed the issue that was not my intention (however useful, I did learn much and I'm happy that it turned out that way). This question asks the intended question more clearly and so should attract different answers.

推荐答案

为什么不只运行它:

SELECT MIN(a) as minA, MAX(a) AS maxA FROM someTable

不幸的是,MySQL不知道窗口函数.因此,如果您真的想选择*以及最小值/最大值,我想您将不得不采用JOIN:

Unfortunately, MySQL doesn't know window functions. So if you really want to select * along with min/max values, I guess you'll have to resort to a JOIN:

SELECT * FROM ( SELECT * FROM someTable ORDER BY a ASC LIMIT 1 ) t1 CROSS JOIN ( SELECT MIN(a) as minA, MAX(a) AS maxA FROM someTable ) t2

或转到子选择,如 Imre L的答案

更多推荐

如何查询具有最低值的行,又如何知道最高值的值?

本文发布于:2023-11-22 20:05:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618819.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最高值   又如   低值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!