对于项目,我们目前正在进行数据库设计。我们认为我们应该在一个表中使用两个auto_increment字段。
表大师:
`pid` int(10) NOT NULL auto_increment,
`iid` int(10) NOT NULL auto_increment,
...
要从备用auto_incremet开始,您可以使用ALTER TABLE tbl AUTO_INCREMENT = 100000;
这仅适用于整个表'tbl'。
pid的auto_increment应为50000000,iid的auto_increment应为80000000
我们希望避免将其拆分为3个表格,其中包含关系主数据 - > table.pid和master - > table.iid。
改变表是不起作用的原因
/* SQL Error (1075): Incorrect table definition; there can be only one auto column and it must be defined as a key */
你有可能或者你推荐什么选择?
答案 0 :(得分:0)
如果您不能使用两个自动列,我认为您必须重新设计数据库。你到底需要什么?
答案 1 :(得分:0)
我不完全理解您的问题,但您可以使用触发器来维护以下关键值:
drop table if exists grid;
create table grid
(
grid_id int unsigned not null auto_increment primary key,
name varchar(255) not null,
next_token_id int unsigned not null default 0,
next_node_id int unsigned not null default 0
)
engine = innodb;
drop table if exists grid_token;
create table grid_token
(
grid_id int unsigned not null,
token_id int unsigned not null,
name varchar(255) not null,
primary key (grid_id, token_id) -- note clustered PK order (innodb only)
)
engine = innodb;
drop table if exists grid_node;
create table grid_node
(
grid_id int unsigned not null,
node_id int unsigned not null,
name varchar(255) not null,
primary key (grid_id, node_id) -- note clustered PK order (innodb only)
)
engine = innodb;
-- TRIGGERS
delimiter #
create trigger grid_token_before_ins_trig before insert on grid_token
for each row
begin
declare tid int unsigned default 0;
select next_token_id + 1 into tid from grid where grid_id = new.grid_id;
set new.token_id = tid;
update grid set next_token_id = tid where grid_id = new.grid_id;
end#
create trigger grid_node_before_ins_trig before insert on grid_node
for each row
begin
declare nid int unsigned default 0;
select next_node_id + 1 into nid from grid where grid_id = new.grid_id;
set new.node_id = nid;
update grid set next_node_id = nid where grid_id = new.grid_id;
end#
delimiter ;
-- TEST DATA
insert into grid (name) values ('g1'),('g2'),('g3');
insert into grid_token (grid_id, name) values
(1,'g1 t1'),(1,'g1 t2'),(1,'g1 t3'),
(2,'g2 t1'),
(3,'g3 t1');
insert into grid_node (grid_id, name) values
(1,'g1 n1'),(1,'g1 n2'),
(2,'g2 n1'),
(3,'g3 n1'),(3,'g3 n2');
select * from grid;
select * from grid_token;
select * from grid_node;