2010-07-27 202 views
3

我想每个表有两个auto_increment列,但mysql只允许一个auto_increment列。所以,我尝试使用我自己的表来复制oracle序列。Mysql自定义序列生成器(如oracle)

这是模式。

create table logical_id_seq (
    logical_id int auto_increment, 
    primary key(logical_id) 
); 

create table mytable (
    physical_id int auto_increment, 
    logical_id int not null references parent(logical_id), 
    data varchar(20), 
    version_start_date datetime not null, 
    version_end_date datetime not null, 
    primary key(physical_id), 
    foreign key (logical_id) references logical_id_seq(logical_id), 
    unique key (logical_id,version_start_date,version_end_date) 
); 

因此,logical_id_seq表被用作序列生成器。

创造新的实体:

  1. 插入新进入logical_id_seq。
  2. 从logical_id_seq读取last_insert_id()。
  3. 使用上面的值在表中插入新行。

让我再给你多一点关于logical_id和physical_id的上下文。我想设计一个时间旅行数据库,这意味着我需要给定任何时间戳(现在或过去)的数据库状态。所以,我有version_start_date和version_end_date。

你能告诉我,如果有我的序列发生器的方法的副作用。

+0

我很困惑。有两个ID列的原因是什么? – Mike 2010-07-27 20:48:39

+0

所以,我想跟踪对行的修改。因此,我使用版本开始和结束日期来跟踪哪一行在任何时间点都是有效的。 – Boolean 2010-07-27 20:53:33

+0

在这个问题中说“thank you”是否是错误的:-) – Boolean 2010-07-27 20:54:40

回答

1

根据你的表类型(IIRC它是MyISAM和BDB),你可以使用一个聪明的技巧与自动增量。

create table component_core ( 
    component_id int auto_increment, 
    primary key(component_id) 
); 

create table component_history ( 
    component_id int not null, 
    version_id int auto_increment, 
    data varchar(20), 
    version_start_date datetime not null, 
    version_end_date datetime not null, 
    primary key(component_id,version_id) 
); 

创建一个全新的部件时插入到component_core,然后使用该插入component_history自动增量ID作为COMPONENT_ID时和VERSION_ID自动增量字段将有从1向上编号为每个不同COMPONENT_ID。在对component_history插入更改时,请使用原始component_id,但允许version_id正常自动增量。在这种情况下,auto_increment列的生成值计算为MAX(auto_increment_column)+ 1 WHERE component_id = given-component_id。

Insert a new component_core 
Retrieve the last autoincremented value from component_core (1) 
Insert a new component_history using the component_id from component_core 
Insert a new component_history using the same component_id 
Insert a new component_history using the same component_id 
Insert a new component_core 
Retrieve the last autoincremented value from component_core (2) 
Insert a new component_history using the component_id from component_core 
Insert a new component_history using the same component_id 

表现在将包含

component_core

component_id 
1 
2 

component_history

component_id version_id 
1   1 
1   2 
1   3 
2   1 
2   2 

不知道,如果技术是任何帮助,特别是我t被限制在特定的表类型(我相信它工作在MyISAM中,但你失去了与MyISAM的事务控制)

编辑

参考:http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html

+0

+1用于自动增量提示。 – Mike 2010-07-27 22:46:41

0

所以,我想跟踪对行的修改(...)

我建议看看Hibernate Envers之前实现自己的解决方案:

的Envers项目旨在实现持久化类的容易审计/ 版本。你所要做的就是用@Audited注释你想要审计的持久化类或它的一些属性。对于每个审计实体,将创建一个表格,该表格将保存对实体所做更改的历史记录。然后您可以毫不费力地检索和查询历史数据。