【问题标题】:Increment a column value based on uniqueness of other column values根据其他列值的唯一性增加列值
【发布时间】:2015-10-10 18:22:23
【问题描述】:

我有一个表,我需要在其中添加一个增量列,但是增量应该基于其他列中的现有值发生。

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 内置的自动增量策略来做到这一点。

【问题讨论】:

    标签: mysql sql database auto-increment


    【解决方案1】:

    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】:

      您可以这样做,将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)
      

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

      【讨论】:

      • 这只会更新一次新列的值。我希望我可以继续保留新行,并且新列自动获取值。
      【解决方案3】:

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

      【讨论】:

      • 谢谢。这似乎是一种更标准的方法。只有这样,我不会让序列生成器表不是临时的。
      猜你喜欢
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2023-01-03
      • 2012-04-17
      相关资源
      最近更新 更多