MySQL 如何从MySql中的表中删除最后一条记录(有条件)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4714239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete last record(on condition) from a table in MySql
提问by Awan
I have a LoginTimetable like this:
我有一个这样的LoginTime表:
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
.
我想删除user_id=1
. 可以识别用户的最后一条记录datetime
。
How can I do this with one query.
我怎么能用一个查询来做到这一点。
回答by Ivan
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:
您需要按 user_id 过滤表(例如 WHERE user_id=1),然后按时间排序(例如 ORDER BY datetime),然后将查询限制为一项(例如 LIMIT 1),然后删除此查询的结果。最后你会得到这样的查询:
DELETE FROM LoginTime WHERE user_id=1 ORDER BY datetime DESC LIMIT 1
回答by nan
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
回答by sarath
DELETE FROM table name
RIGHT JOIN (SELECT COUNT(primary key)
FROM table name)