如果发现重复,MYSQL查询更新字段?

时间:2013-11-18 14:27:04

标签: mysql sql

这是我的问题。我有一张桌子Meaning

ID - Meaning
1 - red car
2 - cat man
3 - red car
4 - ontime
5 - red car
....

我想让列Meaning变得独一无二。所以我想建立一个查询来找到所有的副本和&对于每个重复项,系统应附加[number]以使单元格变得唯一。

因此在运行该查询后,结果应为:

ID - Meaning
1 - red car
2 - cat man
3 - red car [2]
4 - ontime
5 - red car [3]
....

该表非常长约100K行。查询可能类似于此查询

Update Table Meaning set meaning=concat(meaning,"1") 
where meaning in (select meaning from Meaning group by meaning having count(meaning>1)

那么解决问题的查询是什么?

似乎我们必须使用set variable检查每一行?

2 个答案:

答案 0 :(得分:1)

第1步:创建临时表

CREATE TABLE TMP (id int, meaning varchar (2));

第2步:准备查询并插入临时表

insert into tmp 
SELECT id, 
CASE WHEN cnt =0 theN meaning ELSE concat(meaning,'[',cnt+1,']') END AS meaning 

FROM
(
SELECT t1.id, t1.meaning, (

SELECT COUNT( t.id ) 
FROM test t
where  t.meaning=t1.meaning 
and t.id<t1.id
) as cnt
FROM test t1
)TMP

第3步

truncate table test

第4步:迁移到原始

insert into test select * from tmp

答案 1 :(得分:0)

SELECT x.*
     , CONCAT(x.meaning,CASE WHEN COUNT(*) = 1 THEN '' ELSE COUNT(*) END) meaning 
  FROM meanings 
     x JOIN meanings 
     y ON y.meaning = x.meaning 
   AND y.id <= x.id 
 GROUP 
    BY id;