tags:

views:

63

answers:

3

Hi, I would need simply select the last entered row specified by condition,e.g:

SELECT ID from bugs WHERE user=Me

I need to return only the very last ID entered by user 'Me'. Is there any simple way? Thank you

+3  A: 

It would be best to have a TIMESTAMP column that defaults to CURRENT_TIMESTAMP .. it is the only true predictive behavior you can find here.

The second-best thing you can do is ORDER BY ID DESC LIMIT 1 and hope the newest ID is the largest value.

Matt
+1 Matt. Useful pointers.
macek
+1  A: 
SELECT MAX(ID) from bugs WHERE user=Me
SiLent SoNG
A: 

In concurrency, the latest record may not be the record you just entered. It may better to get the latest record using the primary key.

If it is a auto increment field, use SELECT LAST_INSERT_ID(); to get the id you just created.

Wayne
`LAST_INSERT_ID()` is global. It will not return a condition-based ID.
Matt
This **only** works if you do not perform inserting after the row you're trying to query. E.g., if someone registers (`insert into users ...`) then creates a post (`insert into posts ...`), `last_insert_id()` will refer to the last `posts.id`. At this point, there is no way to select the last user using `last_insert_id()`.
macek
ok, I misunderstand the question, thanks.
Wayne