ballouta Posted July 21, 2010 Share Posted July 21, 2010 Hello How can I get the last two entries from 'book' table which has the 'id' as PK and autoincrement? Thank You Quote Link to comment https://forums.phpfreaks.com/topic/208377-last-two-entries/ Share on other sites More sharing options...
bh Posted July 21, 2010 Share Posted July 21, 2010 Hi, Count your rows and then use LIMIT. LIMIT offset, row count Your offset will be "Rownums"-2 so LIMIT "Rownums"-2 Quote Link to comment https://forums.phpfreaks.com/topic/208377-last-two-entries/#findComment-1088941 Share on other sites More sharing options...
Mchl Posted July 21, 2010 Share Posted July 21, 2010 SELECT * FROM tableName ORDER BY ID DESC LIMIT 2 Quote Link to comment https://forums.phpfreaks.com/topic/208377-last-two-entries/#findComment-1088963 Share on other sites More sharing options...
bh Posted July 21, 2010 Share Posted July 21, 2010 @Mchl: yeah, its another solution, but why do you want to order the entire table? if id is a pk thats up to speed, is ok, but i think the counting and then the limit is much lower cost, than your order by. Quote Link to comment https://forums.phpfreaks.com/topic/208377-last-two-entries/#findComment-1088969 Share on other sites More sharing options...
Mchl Posted July 21, 2010 Share Posted July 21, 2010 Right. Just realised your solution will work, but there's something missing from it LIMIT "Rownums"-2,2 Also it's worth noting that COUNT(*) return results instantaneously in MyISAM, but not so in InnoDB. Quote Link to comment https://forums.phpfreaks.com/topic/208377-last-two-entries/#findComment-1088973 Share on other sites More sharing options...
bh Posted July 21, 2010 Share Posted July 21, 2010 I ran a micro test. In a 20K rows table (id, name): SELECT * FROM xyz LIMIT 19998, 2 ~0.0065s SELECT * FROM xyz ORDER BY id DESC LIMIT 0, 2 0.0002s The 2nd is much faster Your right (And at first, still no the count(*) ) [edit] Its understandable, cuz the ids are in sequence (1, 2, 3... 7, ... almost nothing to order. Quote Link to comment https://forums.phpfreaks.com/topic/208377-last-two-entries/#findComment-1088977 Share on other sites More sharing options...
ballouta Posted July 21, 2010 Author Share Posted July 21, 2010 Thank you guys Quote Link to comment https://forums.phpfreaks.com/topic/208377-last-two-entries/#findComment-1089189 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.