我正在寻找一个mysql更新查询,它将两个字段连接在一起然后仍然存在唯一值的位置为每个值添加一个增量并更新第三个字段。如果连接值是唯一的,则它仍然必须在连接中添加1。
实施例
Field1 Field2 UniqueValue
====== ====== ===========
A B AB1
A A AA1
A A AA2
A A AA3
C D CD1
答案 0 :(得分:4)
您可以使用用户变量为每个字段的唯一组合生成递增数,然后将它们连接在一起。
select field1, field2, concat(field, rn) UniqueValue
from (
select
t.*,
@rn := if(@field = field, @rn + 1, if(@field := field, 1, 1)) rn
from
(select
field1, field2,
concat(field1, field2) as field
from your_table
order by field
) t, (select @rn := 0, @field := null) t2
) t;
如果要使用生成的uniqueValue更新表 -
如果您的表中有一个id列,您可以将您的表与上述查询一起加入该ID以进行更新:
update your_table t1 join (
select id, concat(field, rn) UniqueValue
from (
select
t.id,
field,
@rn := if(@field = field, @rn + 1, if(@field := field, 1, 1)) rn
from
(select
id, field1, field2,
concat(field1, field2) as field
from your_table
order by field
) t, (select @rn := 0, @field := null) t2
) t
) t2 on t1.id = t2.id
set t1.uniqueValue = t2.UniqueValue;
如果您没有id列,那么解决此问题的一种方法是使用新表加载新值,然后将其重命名为原始表:
drop table if exists your_table;
drop table if exists your_table_new;
drop table if exists your_table_old;
CREATE TABLE your_table(
Field1 VARCHAR(10) NOT NULL
,Field2 VARCHAR(10)
,UniqueValue Varchar(20)
);
INSERT INTO your_table(Field1,Field2) VALUES ('A','B');
INSERT INTO your_table(Field1,Field2) VALUES ('A','A');
INSERT INTO your_table(Field1,Field2) VALUES ('A','A');
INSERT INTO your_table(Field1,Field2) VALUES ('A','A');
INSERT INTO your_table(Field1,Field2) VALUES ('C','D');
create table your_table_new (field1 varchar(10), field2 varchar(10), uniquevalue varchar(20));
insert into your_table_new (field1, field2, uniqueValue)
select field1, field2, concat(field, rn) UniqueValue
from (
select
t.*,
@rn := if(@field = field, @rn + 1, if(@field := field, 1, 1)) rn
from
(select
field1, field2,
concat(field1, field2) as field
from your_table
order by field
) t, (select @rn := 0, @field := null) t2
) t;
rename table your_table to your_table_old, your_table_new to your_table;