Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select MAX(ID) mysql

Tags:

mysql

group-by

I want to group mysql record with idorig and select the max id in order to select latest record.

My database content is like that:

ID     | IDORIG     | MESSAGE    | STATUS
100    | 100        | azerty     | 2
101    | 100        | azerty     | 1
102    | 100        | azerty     | 1
103    | 100        | azerty     | 0
104    | 104        | azerty     | 0
105    | 104        | azerty     | 0
106    | 104        | azerty     | 0
107    | 104        | azerty     | 0
108    | 104        | azerty     | 0

My SQL request is:

SELECT MAX(id),message,idorig,status FROM messages GROUP BY idorig order by id desc

The sql returns the good id: 102

But problem is that if I try to return status I got 2 not 0

How can I change sql request to get the latest id with group idorig and even get the records of 102 not 100

like image 711
Nathan Avatar asked Sep 23 '14 12:09

Nathan


People also ask

How do I find the max ID 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 do I find max in MySQL?

If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.

How do I get the max ID of a row in SQL?

SELECT row FROM table ORDER BY id DESC LIMIT 1; This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID.


2 Answers

The error takes place bacause MySQL doesn't know which status from grouped records should results you. It knows that you want max(id) from group but according status is not obvious. Some SQL engines would tigger exception but not MySQL. It returns first record from group (status=2 in this case), I guess. You can do it this way

Select id, idorig, message, status where id in (SELECT MAX(id) FROM messages GROUP BY idorig)

MySQL is going to get Max(id) for each group (which is unique) then use it in parent query to select interesting data from this particulars records.

like image 67
Mateusz Nowak Avatar answered Sep 19 '22 15:09

Mateusz Nowak


select ID,idorig,Message,Status from messages order by ID desc limit 1;

or

Select ID,idorig,Message,Status from messages where ID = (select max(ID) from messages);
like image 44
Giles Avatar answered Sep 16 '22 15:09

Giles