1

I need help to write a MySQL query that would do the following for me:

It would select the last row from a certain column. Let's say the table name is 'mysite_codes' and the column name is 'code', there are many rows in this column, but I want the query to take the last added one and get my back one result in PHP (LIMIT 1 thing).

Would anyone please help me with this?

aborted
  • 4,481
  • 14
  • 69
  • 132
  • Possible dup of ["Select last row in MySQL"](http://stackoverflow.com/questions/4073923/select-last-row-in-mysql), ["MySQL - Select the last inserted row easiest way"](http://stackoverflow.com/questions/2770600/mysql-select-the-last-inserted-row-easiest-way), ["Accessing last created row in PHP/MySQL"](http://stackoverflow.com/questions/1358781/accessing-last-created-row-in-php-mysql). – outis Feb 20 '11 at 20:17
  • See also [Select all but the latest row](http://stackoverflow.com/questions/4203213/select-all-but-the-latest-row). – outis Feb 20 '11 at 20:23
  • @outis Don't see the benefit in closing this now. It's been answered. – Lightness Races in Orbit Feb 20 '11 at 23:57
  • @Tomalak: the primary reason for closing a question isn't to prevent answers, it's for any of the reasons listed when you click "close". In this case, the question has been asked before. It's more about SO site structure. – outis Feb 21 '11 at 00:23
  • @outis: I didn't realise that answers would be merged. On that basis, I will join you in voting to close. – Lightness Races in Orbit Feb 21 '11 at 00:42
  • @Tomalak: note that, at this point, answers aren't merged. I think that's a feature that Jon Skeet was once considering but hasn't implemented. Currently, a notice that the question is a duplicate is added at the top of the question, with a link to the duplicated question. This makes the duplicated question rank higher in web searches (and possibly SO site searches; I don't know enough about how the site search is implemented to say). – outis Feb 21 '11 at 02:40

3 Answers3

6

MySQL tables have no inherent sorting. If you want "the last added one" then you'll need an AUTO_INCREMENTing column like id.

Then you can write.

SELECT `code` FROM `mysite_codes` ORDER BY `id` DESC LIMIT 1

to get just the row with the highest id value.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Try this:

select code
  from mysite_codes
 order by add_date desc
 limit 1
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
0

Assuming you have an auto-incremementing id column called something like "auto_id_column":

SELECT code FROM mysite_codes ORDER BY auto_id_column DESC LIMIT 0, 1;
Dave Child
  • 7,573
  • 2
  • 25
  • 37
  • I have an auto-incrementing id column and I'm using the query as above, but now I want to echo out the selected row, how would I do that? – aborted Feb 20 '11 at 20:32
  • Probably best to make that a new question, though I suspect it will have been asked plenty of times before. – Dave Child Feb 20 '11 at 20:35