简体   繁体   中英

Retrieving only the most recent row in MySQL

I have a mysql table with coloumns of name, perf, date_time . How can i retrieve only the most recent MySQL row?

...
ORDER BY `date and time` DESC
LIMIT 1

Note this is not the most recently added row, this is the row with the most "recent" value in the date and time column, which is what I assume you are looking for.

As an alternative:

SELECT *
FROM yourtable
WHERE date_and_time = (SELECT MAX(date_and_time) FROM yourtable)

This one would have the advantage of catching the case where multiple rows were inserted very quickly and ended up with the same timestamp.

SELECT name,
       perf,
       date_and_time
FROM   table
ORDER  BY date_and_time DESC
LIMIT  1 

SELECT * FROM table ORDER BY date, time LIMIT 1

Are date and time separate fields? And would you explain what you mean by "most recent"? If date and time are separate fields or are not refererring to user activity and you mean "most recently updated by user" than you might want to know that time-sensitive tables usually contain a field like "updated_at" which carry a mysql standard timestamp, eg '1989-11-09 12:34:32'. Perhaps you should consider introducing a field like this into your schema. You could than set triggers to update the datetime information like so:

CREATE TRIGGER mytable_update BEFORE UPDATE ON `mytable`
FOR EACH ROW SET NEW.updated_at = NOW();

Of course you could than retrieve the record which has been updated most recently by a select statement as answered above:

ORDER BY `updated_at` DESC LIMIT 1;

In addition, time-sensitive tables usually have a field 'created_at' which carries an unchanging timestamp set when the row is inserted. It is often connected to a trigger like so:

CREATE TRIGGER mytable_create BEFORE INSERT ON `mytable`
FOR EACH ROW SET NEW.created_at = NOW(), NEW.updated_at = NOW(); 

The first trigger above should reflect this and carry the created_at information with an additional statement:

NEW.created_at = OLD.created_at;

If you use a framework (like Django, as you tagged Python), this could be handled by the ORM.

select top 1 * from tablename order by date_and_time DESC (for sql server)

select * from taablename order by date_and_time DESC limit 1(for mysql)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM