View Full Version : [PHP] Display last 2 added Rows
How would I be able to tell MySQL to only display the last 2 recently added rows? Thanks
DarktidesNET
07-13-03, 05:35 PM
SELECT * FROM table_name ORDER BY id DESC LIMIT 2;
THanks for the quick reply. I'll let cha know if it works. =)
DarktidesNET
07-13-03, 05:37 PM
Well, I'm assuming id is a field that is unique. If it doesn't do a "desc <table_name>;" and paste it and I'll fix it.
soapsud
07-13-03, 05:38 PM
do you have a column where they can be arranged somehow? (ie, date, or an ID number that only increments?) i believe that's the only way to search in reverse. the syntax would then be something like:
SELECT * FROM table [WHERE col = 'value'] ORDER BY date DESC LIMIT 2
showing the where just so you can see where it fits into the order by and limit statements...
I always use the field "ID" to identify rows.
soapsud
07-13-03, 06:34 PM
just a caveat though, the auto_incrementing field may not always be appropriate.. ie, if the table gets "fixed" so the new numbers fill in any gaps...
ie.
you have id's
1 2 3 4 7 8 9 10
then eventually, you have your new entries with id's 5 and 6. sorting by id reversed will only get you 10 and 9, and not 5 and 6 (which i assume you'd want)
anyhow, unlikely to happen very often if at all, but still a possibility if the internal pointer gets reset...
interactive
07-13-03, 07:02 PM
Originally posted by Robert:
I always use the field "ID" to identify rows.
Well, on most of my tables I just use an int(11), auto increment. But if you didn't do that I would set up a time field and order it by that.
Originally posted by soapsud:
just a caveat though, the auto_incrementing field may not always be appropriate.. ie, if the table gets "fixed" so the new numbers fill in any gaps...
ie.
you have id's
1 2 3 4 7 8 9 10
then eventually, you have your new entries with id's 5 and 6. sorting by id reversed will only get you 10 and 9, and not 5 and 6 (which i assume you'd want)
anyhow, unlikely to happen very often if at all, but still a possibility if the internal pointer gets reset... It will not make 5 and 6 it will make 11 and 12.
soapsud
07-21-03, 06:05 PM
sorry i should have been a bit clearer. in normal operation yes 11 and 12, but in this specific case (ie, can you rely on the auto_increment number to always be larger than previous ones) the answer is no, if the internal pointer gets reset it will "fill in the blanks" if there are any to be done (and thus the 5 and 6 example)
sorry for any confusion
vBulletin v3.5.4, Copyright ©2000-2012, Jelsoft Enterprises Ltd.