I have a LoginTime table like this:
id | user_id | datetime
1 | 1 | 2011-01-17 18:51:05
2 | 1 | 2011-01-18 18:51:05
3 | 1 | 2011-01-19 18:51:05
4 | 2 | 2011-01-19 18:51:05
I want to delete last record for user_id=1
. Last record of a user can be recognized by datetime
.
How can I do this with one query.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted.
The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause. Syntax: Basic.
You need to filter the table by user_id (eg WHERE user_id=1), then sort it by time (eg ORDER BY datetime) and then limit the query to just one item (eg LIMIT 1) and you delete the result of this query. At the end youl get query like this:
DELETE FROM LoginTime WHERE user_id=1 ORDER BY datetime DESC LIMIT 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With