Mysql删除重复行+排序条件

时间:2015-09-20 14:31:56

标签: 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较差的行

谢谢

2 个答案:

答案 0 :(得分:1)

您希望保持 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;

答案 1 :(得分:0)

我认为这可能会有所帮助

DELETE t1
  FROM t1 as tb1
  join t1 as tb2
 WHERE tb1.url= tb2.url
   and tb1.id < tb2.id

这样,您可以使用id列

上的最大值保留记录

但如果您只想获取记录

SELECT distinct tb1.*
  FROM t1 as tb1
  join t1 as tb2
 WHERE tb1.url= tb2.url
   and tb1.id < tb2.id