Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the Max and Min records in one MySQL command

Tags:

I need to be able to select two records from a table based on ID.

I need the first one, and the last one (so min, and max)

Example:

Customer         ID   NAME         1     Bob         50    Bob 

Any ideas? Thanks.

like image 702
TheBounder Avatar asked Nov 23 '10 09:11

TheBounder


2 Answers

SELECT MIN(id), MAX(id) FROM tabla 

EDIT: If you need to retrive the values of the row you can do this:

SELECT * FROM   TABLA AS a, (SELECT MIN(id) AS mini,                             MAX(id) AS maxi                      FROM   TABLA) AS m WHERE  m.maxi = a.id        OR m.mini = a.id; 
like image 134
SubniC Avatar answered Oct 13 '22 22:10

SubniC


Is this what you are looking for?

select id, name from customers where id = ( select max(id) from customers ) union all select id, name from customers where id = ( select min(id) from customers ) 

Now I have tested this type of query on a MySQL database I have access, and it works. My query:

SELECT nome, livello FROM personaggi WHERE livello = ( SELECT max( livello ) FROM personaggi )  
like image 35
Albireo Avatar answered Oct 13 '22 23:10

Albireo