Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get more info from a MAX(ID), MIN(ID) MYSQL query?

Tags:

mysql

max

min

How to get more columns from MAX(ID), MIN(ID) MYSQL query?

Currently I get only two values: MAX(ID) & MIN(ID) from this query:

SELECT MIN(ID), MAX(ID) FROM mytable WHERE mytable.series = 'white' ;

Need to get something like this-pseudo-query:

SELECT  column1, column2
FROM    mytable 
WHERE   series = 'white'
AND ID=Max(ID)
'AND GET ME ALSO'
WHERE   series = 'white'
AND ID=Min(ID);`

It should return 2 rows for the column 'series' that equals 'white'.

1st with column1 and column2 for ID=Min(ID). 2nd with column1 and column2 for ID=Max(ID).

But how?

like image 603
Ash501 Avatar asked Jul 31 '12 17:07

Ash501


People also ask

How do you find the max and min value in MySQL?

MySQL MIN() and MAX() FunctionsThe MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.

How to filter MAX value in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

What is Max ID in MySQL?

MySQL supports two-byte collation IDs. The range of IDs from 1024 to 2047 is reserved for user-defined collations.

How to find the largest number in a column in SQL?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.


1 Answers

Here is an approach using UNION:

SELECT column1, column2
FROM mytable
WHERE series = 'white' AND ID IN
(    
    SELECT MIN(ID) FROM mytable WHERE series = 'white'
    UNION
    SELECT MAX(ID) FROM mytable WHERE series = 'white'
)

For good performance add a combined index on (series, id).

Or another variation which may have better performance:

(
    SELECT column1, column2
    FROM mytable
    WHERE series = 'white'
    ORDER BY ID
    LIMIT 1
)
UNION
(
    SELECT column1, column2
    FROM mytable
    WHERE series = 'white'
    ORDER BY ID DESC
    LIMIT 1
)

This will also be able to use the combined index on (series, id).

like image 152
Mark Byers Avatar answered Nov 11 '22 09:11

Mark Byers