簡體   English   中英

mysql刪除行,保留每個user_id的最后5個

[英]mysql delete rows keeping the last 5 for the each user_id

我有一個mysql表(“c5_imgs”),其中包含“user_id”(varchar)和“date”(時間戳)列。 此特定表中的數據量增長遠遠超過我最初的預期,現在我正在嘗試刪除除最近5之外的每個user_id的所有記錄。

對於給定的user_id,我可以獲取要刪除的行:

select *
FROM c5_imgs i
where 
    date < (
        select date 
        from c5_imgs i2 
        where i.user_id = i2.user_id 
        order by i2.date desc
        limit 4,1
    )
and user_id = 'xxx'

但我在刪除這些行時遇到問題:

delete
FROM c5_imgs
where 
    date < (
        select date 
        from c5_imgs i2 
        where 'xxx' = i2.user_id 
        order by i2.date desc
        limit 4,1
    )
and user_id = 'xxx'

#1093 - You can't specify target table 'c5_imgs' for update in FROM clause

我想為所有user_id做一個通用查詢,而不是一次一個...任何幫助將不勝感激,謝謝。

編輯 :chetan的回答幫助我刪除了一個user_id,但我正在為所有user_id尋找更通用的解決方案。

Edit2 :我最終使用的查詢是基於Christian的答案:

delete aa.* 
from c5_imgs aa,
(
select distinct c.user_id as user_id,
    (select x.date 
    from c5_imgs as x
    where x.user_id = c.user_id
    order by x.date desc
    limit 4,1) as date
from c5_imgs as c
) bb
where aa.user_id = bb.user_id and aa.date < bb.date

你可以使用join來做到這一點。 例如

delete a.*
FROM c5_imgs a, (
        select date 
        from c5_imgs
        where 'xxx' = user_id 
        order by date desc
        limit 4,1
    ) b
where 
    a.date < b.date
and a.user_id = 'xxx';

我沒有運行此查詢,但它應該工作。 必要時可以解決。

您可以分三步完成:

第一

create table aux
select distinct c.user_id as user_id,
    (select x.date 
    from c5_imgs as x
    where x.user_id = c.user_id
    order by x.date desc
    limit 4,1) as date
from c5_imgs as c;

第二

delete c5_imgs
from c5_imgs as c
inner join aux as a on a.user_id = c.user_id
where  c.date < a.date;

第三

drop table aux;

如果使用大表,可以在aux表的列上創建索引以加快刪除操作。

CREATE INDEX aux_idx1 ON aux(user_id);
CREATE INDEX aux_idx2 ON aux(date);

請注意,如果您有一個可以從中獲取不同用戶ID的用戶表,則可以簡化並提高第一步的速度。

這並不能保證准確保留5張最新圖像。 如果第5個和下一個位置的多個圖像的日期完全相同,則無法按要求運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM