根据其他列值的唯一性增加列值

时间:2015-07-21 10:34:19

标签: mysql sql database auto-increment

我有一个表,我需要添加一个增量列,但增量应该根据其他列中的现有值进行。

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来实现此目的。

3 个答案:

答案 0 :(得分:1)

使用带有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

答案 1 :(得分:0)

MySQL中没有内置的增量方法,但您可以使用相关的子查询或变量来执行此操作:

select t.*,
       (@rn := if(@c = concat(first_col, ':', second_col), @rn + 1,
                  @c := concat(first_col, ':', second_col), 1, 1
                 )
       ) as new_col
from mytable t cross join
     (select @rn := 0, @c := '') params
order by first_col, second_col;

注意:这会重新排序结果。如果您希望结果按原始顺序排列,那么您需要一个指定排序的列。

答案 2 :(得分:0)

以下是您可以执行此操作的方法,将col1valcol2val替换为要插入的值。

INSERT INTO mytable (first_col, second_col, new_col)
VALUES (SELECT col1val, col2val SUM(COUNT(*), 1)
        FROM mytable
        GROUP BY first_col, second_col
        HAVING first_col = col1val AND second_col = col2val)

请注意,这是一个插入查询,只会影响新插入的值。