Question:
How can I get a mysql query to return with the latest record's fieldname value?
kpa4941
2009-10-20 18:12:34 UTC
I am trying to make a "Latest member" info thing for a php script, and I want it to get the lastest record(user) with the test under the field name "username". Thanks!
Three answers:
Scott
2009-10-21 07:23:35 UTC
Ok, I'll append to what the other guys said, but with an question:



What are you going to use to determine the newest user ? The autoincemented id (if you have one)? A date field like 'dateEntered' ?



Once you determine that, to get the record, you'd do something like:



select id, firstname, lastname

from users

where id = ( select max (id ) from users );



Good luck.
harvestall
2009-10-20 20:24:07 UTC
If your primary key is auto incremented, then the latest entry will be the entry with the greatest primary key. You could use a mySQL statement like:



SELECT * FROM table ORDER BY id DESC LIMIT 1



Which will return the row with the greatest id.



There's probably a better way to do this, but I'm not sure right now.
Jim
2009-10-20 18:24:10 UTC
a mysql stored procedure (LAST_INSERT_ID()) and a php function (mysql_insert_id) both exist for this. but it is the last inserted record's id, which should be auto_increment and probably PRIMARY KEY.



I suggest the fieldname id in either BIGINT or INT.

INT id AUTO_INCREMENT NOT NULL PRIMARY KEY,


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...