我有一个表,我需要向其中添加一个增量列,但是增量应该基于其他列中的现有值。
select * from mytable;
first_col second_col
A B
A C
A D
A E
A B
A D
现在,我想添加另一列,比如 new_column,其值在 first_col 和 second_col 的基础上唯一递增。
该列应该像这样填充:
first_col second_col new_col
A B 1
A C 1
A D 1
A E 1
A B 2
A D 2
A B 3
是否可以在内置的自动增量策略中使用某种 MySQL 来做到这一点。
最佳答案
使用带有 auto_incremented id 列的临时表
create temporary table tt (
id int auto_increment primary key,
col1 varchar(32),col2 varchar(32));
insert into tt
select col1, col2 from origtable;
select col1, col2,
(select count(*)+1 from tt s
where s.col1=m.col1 and s.col2=m.col2
and s.id<m.id) n
frm tt m
关于mysql - 根据其他列值的唯一性增加列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31536654/