首页  编辑  

如何获取MySQL数据表中,最后若干行数据?

Tags: /MySQL/   Date Created:
如何获取MySQL数据表中,最后若干行数据,不改变表结构,不排序?
How to select the last N record from MySQL table using SQL syntax?
How to select the Last row from a table..using Mysql
How to fetch the last record from the table in mysql without order by?
The question asked there:
http://stackoverflow.com/questions/7203813/how-to-fetch-the-last-record-from-the-table-in-mysql-without-order-by 
But closed, so I answered here:

Answer:
The quick, simple way, and the fast way without order, needn't an ID column or change table structure:
-- Get Last N record from a MySQL Table
SET @N = 100;
SET @offset = (SELECT COUNT(*) FROM table_name) - @N;
SET @offset = IF(@offset > 0, @offset, 0);
PREPARE s FROM 'select * from table_name limit ? offset ?';
EXECUTE s USING @N, @offset;