Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete last record(on condition) from a table in MySql

Tags:

sql

mysql

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.

like image 245
Awan Avatar asked Jan 17 '11 14:01

Awan


People also ask

Which clause is used in delete query?

You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted.

What is delete clause?

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.


1 Answers

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
like image 91
Ivan Avatar answered Oct 08 '22 08:10

Ivan