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

2019-03-20 07:05发布

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.

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?

标签: sql mysql max min
2条回答
做个烂人
2楼-- · 2019-03-20 07:25
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:

SELECT column FROM table
LIMIT 10 OFFSET 20

The above query will return rows 20-30.

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

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.

查看更多
欢心
3楼-- · 2019-03-20 07:41

Have you tried :

SELECT min(price) as min_price, max(price) as max_price FROM 
    (SELECT price FROM `prices` LIMIT 0,10);
查看更多
登录 后发表回答