How can I
SELECT
the last row in a MySQL table?
I'm
INSERT
ing data and I need to retrieve a column value from the previous row.
There's an
auto_increment
in the table.Answers
Yes, there's an auto_increment in there
If you want the last of all the rows in the table, then this is finally the time where
MAX(id)
is the right answer! Kind of:SELECT fields FROM table ORDER BY id DESC LIMIT 1;
on tables with many rows are two queries probably faster...
SELECT @last_id := MAX(id) FROM table;
SELECT * FROM table WHERE id = @last_id;
Make it simply use:
PDO::lastInsertId
SELECT * FROM adds where id=(select max(id) from adds);
This query used to fetch the last record in your table.
Why is everyone referring to order, max, etc?
That's not very cpu friendly considering millions and millions of entries.
A more efficient solution would be making a trigger that adds to a row in a separate table.
This way you can get the value at O(1) time .
0 comments:
Post a Comment