【问题标题】:How to delete the row that has least value in a specific column if group by count of the column is greater than 1如果按列计数大于1,如何删除特定列中值最小的行
【发布时间】:2020-12-06 19:41:54
【问题描述】:

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

我想删除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);

这不起作用。

【问题讨论】:

标签: mysql sql duplicates sql-delete


【解决方案1】:

如果你想使用二维,你必须使用 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);

【讨论】:

    【解决方案2】:
    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

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 1970-01-01
      • 2019-12-25
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 2014-12-26
      相关资源
      最近更新 更多