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 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
DELETE FROM logintime t1
JOIN
(
SELECT MAX(datetime)
AS max_dt
FROM logintime
WHERE user_id = 1
) t2
WHERE t1.datetime = t2.max_dt
AND user_id = 1
DELETE FROM table name
RIGHT JOIN (SELECT COUNT(primary key)
FROM table name)
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.