从MYSQL中删除数据

时间:2017-04-12 07:02:26

标签: mysql

我有一个表,其中包含MySQL中的数据。 Size以MB为单位显示文件大小。

--------------------------------------------
| id  | name | size | user_id | created_at |
--------------------------------------------
| 1   | a    | 120  | 1       | 2017-04-03 |
--------------------------------------------
| 2   | b    | 280  | 1       | 2017-04-04 |
--------------------------------------------
| 3   | c    | 220  | 1       | 2017-04-05 |
--------------------------------------------

现在,如果特定用户超过500MB的限制,我想删除最旧的数据。在上述情况下,ID#1需要删除。

有人可以帮我写一个查询吗?

1 个答案:

答案 0 :(得分:2)

您可以分三步构建查询。首先,为每个用户提供以后加载文件的日期为500MB阈值:

select  t1.user_id, t1.created_at
from    files t1
join    files t2
on      t1.user_id = t2.user_id and
        t2.created_at > t1.created_at
group by t1.user_id, t1.created_at
having  sum(t2.size) >= 500

然后,对于每个用户,您将获得更高的日期

select  user_id, max(created_at)
from    (
            select  t1.user_id, t1.created_at
            from    files t1
            join    files t2
            on      t1.user_id = t2.user_id and
                    t2.created_at > t1.created_at
            group by t1.user_id, t1.created_at
            having  sum(t2.size) >= 500
        )

最后,通过将其与源表连接,将其用作实际delete的参考:

delete t1
from   yourTable t1
join   (
            select  user_id, max(created_at) as created_at
            from    (
                        select  t1.user_id, t1.created_at
                        from    files t1
                        join    files t2
                        on      t1.user_id = t2.user_id and
                                t2.created_at > t1.created_at
                        group by t1.user_id, t1.created_at
                        having  sum(t2.size) >= 500
                    )
       ) t2
on     t1.user_id = t2.user_id and
       t1.created_at = t2.created_at

修改

Working Rextester