删除记录

时间:2011-06-29 08:23:30

标签: mysql sql-delete

我有一个表[user_logs],其中包含以下字段[username],[datetimelog]

样本数据

==============
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

我想知道如何创建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

3 个答案:

答案 0 :(得分:0)

怎么样:

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.

这可行吗?

答案 1 :(得分:0)

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

这里删除一行,如果它不是具有相同user_id的组中的最长时间

答案 2 :(得分:0)

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

试试