簡體   English   中英

如果image_id計數大於5則刪除?

[英]Delete if image_id count is greater than 5?

我有桌子

id color      image_id
1   red          2
2   green        2
3   pink         2
4   black        2
5   gray         2
6   orange       2
7   purple       2
8   yellow       2
9   greenish     2
10  white        2

select image_id,count(image_id) from colors group by image_id having count(image_id) > 5

如果count大於5則刪除大於5的數據

6   orange       2
7   purple       2
8   yellow       2
9   greenish     2
10  white        2

它應該被刪除

delete from colors
where id not in 
(select id
from colors 
order by id
limit 5)

您要保留每個圖像ID的前五行。 這是使用變量的方法:

delete i
    from images i join
         (select i.*,
                 (@rn := if(@id = id, @rn + 1,
                            if(@id := id, 0, 0)
                           )
                 ) as rn
          from images i cross join
               (select @id := 0, @rn := 0) vars
          order by image_id, id
         ) ii
         on ii.id = i.id 
    where ii.rn > 5;

您可以使用子查詢,然后基於內部聯接進行刪除,例如,它將僅刪除具有聯接的記錄,而在子查詢中,您僅會帶回要刪除的記錄。

delete a
from colors a
inner join
(
select image_id,count(image_id) from colors group by image_id having count(image_id) > 5
) as b
on a.image_id = b.image_id

以下查詢將刪除除具有最低ID的前5種顏色以外的所有圖像顏色。

delete from colors where id in (
    select id from (
        select c1.id from colors c1
        join colors c2 on c1.image_id = c2.image_id and c2.id < c1.id
        group by c1.id
        having count(*) >= 5
    ) t1
)

暫無
暫無

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

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