重复时更改字段

时间:2012-09-10 18:00:35

标签: mysql

  

可能重复:
  Renaming the duplicate data in sql

我必须清理一个表字段(article_title),创建一个新字段,其中重复的标题会被更改:

 id  |      title         |     new_title
 34  | My Duplicate Title | My Duplicate Title
 ...
 95  | My Duplicate Title | My Duplicate Title (2)

我使用了这个mysql查询,但它不起作用(所有等级都是1):

 SET @rank := 0;

 SET @prev := NULL;

 SELECT @rank := IF(@prev = title, @rank + 1, 1) AS rank,
   id, IF(@rank>1, Concat(title, ' (', @rank, ')'), title), @prev := title
 FROM articles ORDER BY title ASC

我做错了什么?

1 个答案:

答案 0 :(得分:0)

drop table if exists t;
drop table if exists t2;
create table t( id integer ,title varchar(50), new_title varchar(50));
insert into t (id, title) values (34, 'My Duplicate Title'), (95, 'My Duplicate Title');
create temporary table t2 (id integer, new_title varchar(50));
insert into t2 (id, new_title)
select id, concat( title, 
  ' (', 
    (select count(*) from t as tt where tt.title = t.title and tt.id > t.id), 
    ')' 
) from t;
update t, t2
set t.new_title = t2.new_title where t.id=t2.id;