【问题标题】:auto_increment column for a group of rows?一组行的自动增量列?
【发布时间】:2012-03-08 22:56:47
【问题描述】:

我想弄清楚如何做一个有 3 列的表格:

unique_id, type, version

其中 unique_id 是每个记录的 AUTO_INCREMENT,版本是每个类型的 AUTO_INCREMENT。

目的是,当我插入时,我只需要指定“类型”,并且会自动生成 unique_id 和 version_id。例如:

insert type 'a', then values are:  1 , a , 1
insert type 'a', then values are:  2 , a , 2
insert type 'a', then values are:  3 , a , 3
insert type 'b', then values are:  4 , b , 1
insert type 'b', then values are:  5 , b , 2
insert type 'a', then values are:  6 , a , 4

还可以公平地说,这样的设置并没有真正标准化吗?而是应该是两张表?

【问题讨论】:

  • 这不是版本的自动递增,因为它不会在每次插入时递增。您正在谈论触发存储过程的触发器。它可以作为子表完成,在这种情况下,版本将不在此表中,而是在子表中。尽管如此,它仍然不会自动增加版本。

标签: mysql auto-increment


【解决方案1】:

您不能为每种类型自动生成序列,但您可以生成自己的序列。

insert into the_table (type, version)
select 'a', 1 + IFNULL(max(version), 0)
  from the_table
  where type = 'a';

【讨论】:

  • 太棒了!!给定a 是来自给定语言的变量。如果where type = 'a' 可能不会返回任何内容,您还应该返回0 而不是max(version)。 +1
【解决方案2】:

如果表格有很多行(具体取决于您要执行的操作),那么最好为每个版本设置单独的表格。然后,将每种类型插入到相应的版本表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    相关资源
    最近更新 更多