选择最后一行,无需任何键 [英] Selecting last row WITHOUT any kind of key
问题描述
我需要获取表中的最后(最新)行(使用MySQL的自然顺序-即我没有任何类型的ORDER BY子句就得到的内容),但是没有键可以对ORDER BY进行操作!
I need to get the last (newest) row in a table (using MySQL's natural order - i.e. what I get without any kind of ORDER BY clause), however there is no key I can ORDER BY on!
表中唯一的键"是索引的MD5字段,因此我不能对此进行真正的ORDER BY.没有时间戳,自动增量值或我可以轻松对其进行排序的任何其他字段.这就是为什么我只保留自然排序顺序作为最新"指标的原因.
The only 'key' in the table is an indexed MD5 field, so I can't really ORDER BY on that. There's no timestamp, autoincrement value, or any other field that I could easily ORDER on either. This is why I'm left with only the natural sort order as my indicator of 'newest'.
而且,不幸的是,更改表结构以添加适当的auto_increment是不可能的. :(
And, unfortunately, changing the table structure to add a proper auto_increment is out of the question. :(
任何人都知道如何使用普通SQL来完成此操作,或者我是SOL?
Anyone have any ideas on how this can be done w/ plain SQL, or am I SOL?
推荐答案
如果是MyISAM,则可以在两个查询中完成
If it's MyISAM you can do it in two queries
SELECT COUNT(*) FROM yourTable;
SELECT * FROM yourTable LIMIT useTheCountHere - 1,1;
但是,这是不可靠的,因为
This is unreliable however because
- 假定行仅添加到该表中,而从不删除.
- 假设与此同时没有对该表执行任何其他写操作(您可以锁定该表)
- 可以使用ALTER TABLE重新排序MyISAM表,因此不再保留插入顺序.
在InnoDB中根本不可靠,因为此引擎可以随意对表进行重新排序.
It's not reliable at all in InnoDB, since this engine can reorder the table at will.
这篇关于选择最后一行,无需任何键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!