从 MySQL 表的一部分中选择最小值和最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4957786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:42:34  来源:igfitidea点击:

SELECT min and max value from a part of a table in MySQL

sqlmysqlmaxmin

提问by Taras Bulgakov

If I want to select min and max values from a whole table I can use this:

如果我想从整个表中选择最小值和最大值,我可以使用这个:

SELECT min(price) as min_price, max(price) as max_price FROM `prices`

But how to select min and max values from just a part of a table? For example, I have 30 rows in a table. I want to select min and max values from first ten rows, then from second ten rows and then form the last 10.

但是如何从表格的一部分中选择最小值和最大值?例如,我在一个表中有 30 行。我想从前十行中选择最小值和最大值,然后从后十行中选择最后 10 行。

I've tried something like

我试过类似的东西

SELECT min(price) as min_price, max(price) as max_price FROM `prices` LIMIT 0,10

but this did not work.

但这不起作用。

How can I solve this problem with minimum queries?

如何以最少的查询解决此问题?

回答by reggie

SELECT MIN(PRICE) AS MinPrice, MAX(PRICE) AS MaxPrice FROM (SELECT PRICE FROM PRICES LIMIT 10) tmp;

moreover, MySQL have a cool feature that will let you return an arbitrary range of rows (eg return rows 10-20). This is very handy for displaying pages of records:

此外,MySQL 有一个很酷的特性,可以让你返回任意范围的行(例如返回行 10-20)。这对于显示记录页面非常方便:

SELECT column FROM table
LIMIT 10 OFFSET 20

The above query will return rows 20-30.

上述查询将返回第 20-30 行。

So in short, to return rows from 20 to 30 in case of your query, you use:

简而言之,要在查询时返回 20 到 30 行,您可以使用:

SELECT MIN(PRICE) AS MinPrice, MAX(PRICE) AS MaxPrice 
FROM (SELECT PRICE FROM PRICES LIMIT 10 OFFSET 20);

YOU need to change the offset value to specify the start point of your range.

您需要更改偏移值以指定范围的起点。

回答by Shikiryu

Have you tried :

你有没有尝试过 :

SELECT min(price) as min_price, max(price) as max_price FROM 
    (SELECT price FROM `prices` LIMIT 0,10);