Deleting Records

你。 提交于 2019-12-02 09:38:01

问题


I have a table [user_logs] with the following fields [username], [datetimelog]

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

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

回答1:


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?




回答2:


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




回答3:


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

Try that



来源:https://stackoverflow.com/questions/6517664/deleting-records

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!