Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

max

min

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?

like image 547
Taras Bulgakov Avatar asked Feb 10 '11 13:02

Taras Bulgakov


2 Answers

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.

like image 80
reggie Avatar answered Sep 24 '22 06:09

reggie


Have you tried :

SELECT min(price) as min_price, max(price) as max_price FROM 
    (SELECT price FROM `prices` LIMIT 0,10);
like image 25
Shikiryu Avatar answered Sep 24 '22 06:09

Shikiryu