如果按列计数分组大于1,如何删除特定列中值最小的行

问题描述

我有一个如下表所示的名称推荐

enter image description here

我要删除cnt为最小值并且存在ID_recipient多个记录的所有行。

如果只有一条记录ID_recipient,则无论cnt的值如何,都不应删除它。

蓝色突出显示的是必须保留的记录。

我尝试过:

DELETE from table where( 
    SELECT disTINCT(A.ID_recipient),disTINCT(A.cnt) FROM (
          SELECT  MIN(cnt) as cnt FROM recomendation_table_ID_recipient GROUP BY ID_recipient HAVING COUNT(*) > 1 ) as A);

这不起作用。

解决方法

如果要使用2维,则必须使用IN子句。

您的子查询没有多大意义,因此您应该先进行测试,或者发布带有所需示例的数据

DELETE from recomendation_table_ID_recipient where (ID_recipient,cnt) IN ( 
    SELECT DISTINCT A.ID_recipient,A.cnt FROM (
          SELECT ID_recipient,MIN(cnt) as cnt FROM recomendation_table_ID_recipient GROUP BY ID_recipient HAVING COUNT(*) > 1 ) as A);
,
delete t1 from recomendation_table_ID_recipient t1 join (
    select ID_recipient,min(cnt) as cnt from recomendation_table_ID_recipient
    group by ID_recipient
    having count(*) > 1
) t2 on t1.ID_recipient = t2.ID_recipient and t1.cnt = t2.cnt;

See db-fiddle