我有桌子
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
应该删除
答案 0 :(得分:2)
delete from colors
where id not in
(select id
from colors
order by id
limit 5)
答案 1 :(得分:1)
您希望为每个图片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;
答案 2 :(得分:1)
您可以使用子查询,然后根据内部联接删除,例如它只会删除它有连接的记录,而在你的子查询中你只会带回你要删除的记录。
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
答案 3 :(得分:1)
以下查询将删除除了具有最低颜色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
)