简体   繁体   English

删除记录

[英]Deleting Records

I have a table [user_logs] with the following fields [username], [datetimelog]我有一个表 [user_logs],其中包含以下字段 [用户名]、[日期时间日志]

Sample Data样本数据

==============
user1   2011-06-28 08:49:01
user2   2011-06-28 08:59:38
user3   2011-06-28 09:04:31
user4   2011-06-28 10:00:15
user2   2011-06-28 10:28:54
user1   2011-06-29 08:31:22
user9   2011-06-29 08:32:32
user2   2011-06-29 10:13:53
user1   2011-06-29 13:11:15

I want to know how to create an SQL Delete query to delete all user logs EXCEPT their last log so that the above example will produce the following after a DELETE query我想知道如何创建 SQL 删除查询以删除所有用户日志(除了他们的最后一个日志),以便上面的示例在 DELETE 查询后产生以下内容

user1   2011-06-29 13:11:15
user2   2011-06-29 10:13:53
user3   2011-06-28 09:04:31
user4   2011-06-28 10:00:15
user9   2011-06-29 08:32:32

What about:关于什么:

DELETE FROM 
    MY_TABLE M -- delete from the table
LEFT JOIN
    MY_TABLE M2 ON M.user = M2.user -- table needs to be joined TO ITSELF
WHERE
    NOT M.LOG_DATE = MAX( M2.LOG_DATE ) -- Anything which isn't MAX goes.

Could that work?那能行吗?

DELETE FROM table a WHERE time != (SELECT MAX(time) FROM table b WHERE b.user=a.user);

Here delete a row, if its not the maximum time in group with the same user_id这里删除一行,如果它不是具有相同 user_id 的组中的最长时间

DELETE from user_logs UL1, user_logs UL2
where UL1.username =UL2.datetimelog
and UL1.datetimelog < UL2.datetimelog

Try that试试看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM