简体   繁体   English

从MYSQL删除数据

[英]Remove data from MYSQL

I have a table which contains data as below in MySQL. 我有一个表,其中包含如下MySQL中的数据。 Size shows file's size in MB. 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 |
--------------------------------------------

Now, I want to delete the oldest data if a particular user has crossed the limit of 500MB. 现在,如果特定用户超过了500MB的限制,我想删除最早的数据。 In above case, ID#1 needs to remove. 在上述情况下,需要删除ID#1

Can anyone please help me to write a query? 谁能帮我写一个查询吗?

You can build a query for that in three steps. 您可以通过三个步骤为此建立查询。 First, you get for each user the dates that have files loaded later the 500MB threshold: 首先,您为每个用户获得的文件加载日期为后来的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

Then for each user you get the higher of those dates 然后,对于每个用户,您将获得较高的日期

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
        )

Finally, you use that as reference for the actual delete , by joining it with the source table: 最后,通过将其与源表结合起来,将其用作实际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

Edit 编辑

Working Rextester 上个月工作

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

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