How to get last row value in mysql database

I have a MySQL table with the following data (sample);

UserId  -   DeviceId    -   StartDate   -   EndDate
------------------------------------------------------
1001        D119822         11/27/2011      12/02/2011
1001        D198726         11/27/2011      12/02/2011
1001        D552833         11/27/2011      12/02/2011
1001        D980993         11/27/2011      12/02/2011

I was looking for some thing row_numor ordinal_position, but did not find anything. How can I get the last record from the above table without adding a serial / auto increment column?

+5
source share
3 answers

Try this query, I tested it and it works for me.

select s.*, @rownum:=@rownum+1 as rank
from your_table s, (SELECT @rownum:=0) r
order by rank DESC
LIMIT 1;
+4
source

"last" can be alphabetic, time, meaning, etc. You need to determine what in a simple query:

SELECT *
FROM Mytable
ORDER BY (some criteria that defines "last") DESC
LIMIT 1;
+4
source

, . MySQL , , .

You can add a column that automatically increments (unique identifier) ​​when a row is inserted, or you can add a timestamp column to track the time at which the row was inserted.

If you are not allowed to manipulate the table, perhaps you can add a new table to store the last row of data added (but this is a really bad solution).

+3
source

All Articles