Select last row in MySQL

2019-01-02 14:51发布

How can I SELECT the last row in a MySQL table?

I'm INSERTing data and I need to retrieve a column value from the previous row.

There's an auto_increment in the table.

标签: mysql
9条回答
像晚风撩人
2楼-- · 2019-01-02 15:51

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;
查看更多
孤独寂梦人
3楼-- · 2019-01-02 15:52

You can use an OFFSET in a LIMIT command:

SELECT * FROM aTable LIMIT 1 OFFSET 99

in case your table has 100 rows this return the last row without relying on a primary_key

查看更多
深知你不懂我心
4楼-- · 2019-01-02 15:55

on tables with many rows are two queries probably faster...

SELECT @last_id := MAX(id) FROM table;

SELECT * FROM table WHERE id = @last_id;
查看更多
登录 后发表回答