mysql删除重复行+排序条件

标签 mysql duplicates conditional-statements

我试图从我的 Mysql 表中删除一些行,当一个键重复时(这里是“url”)并保留一个特定的行(这里是最小的“key1”和“key2”)

示例:

Table t1
Id    Url    Key1    Key2
1     A.com   10      10
2     B.com   20      25
3     B.com   21      25
4     C.com   35      35
5     C.com   35      37

期望的输出是:

Table t1
Id    Url    Key1    Key2
1     A.com   10      10
3     B.com   21      25
5     C.com   35      37

所以查询(如果存在的话)应该是这样的:

  • 选择 Url 重复的行
  • 然后按Key1排序,去掉Key1严格劣后的行
  • 如果Key1相等,则去掉Key2次的行

谢谢

最佳答案

您想保留 key1key2 最大的行。一种简单的表达方式是:

delete t1 from table t1
    where exists (select 1
                  from t1 t11
                  where t11.url = t1.url and
                        (t11.key1 > t1.key1 or
                         t11.key1 = t1.key1 and t11.key2 > t1.key2
                        )
                 );

唉,MySQL 不允许这种构造,因为你正在使用被删除的表。所以,你可以这样做:

delete t1
    from t1 left join
         (select t.*,
                 (select max(key2)
                  from t1
                  where t1.url = t.url and t1.key = t.maxkey1
                 ) as maxkey2
          from (select url, max(key1) as maxkey1
                from t1
                group by url
               ) t
        ) t
        on t1.url = t.url and t1.key1 = t.maxkey1 and t2.key2 = t.maxkey2
    where t.url is null;

关于mysql删除重复行+排序条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32680495/

相关文章:

mysql - 将同一张表中的两个 SELECT 合并为一个?

php - 将多个复选框值插入 MySQL

sql-server - 连接 2 个表时排除输出中重复列的 T-SQL 语法是什么?

php - 使用 implode 从联接表上的 mysql_query 生成 csv 文件,输出给出重复的字段?

mysql - SQL如何删除特定列的重复行并保留一个

Java Regex 一组中的字符数决定了下一组中的字符数

java - CompareTo() 在客户端/服务器应用程序中给出相互冲突的结果?

Mysql WHERE 字段包含 JSON 变量

mysql - 使用 common_schema 库无法解析 json 数组值

R矩阵行选择中的多个条件