Mysql - 具有diff行为的第二个auto_increment col

时间:2010-03-25 15:25:11

标签: mysql

我有这样的提议表 - ID(auto_increment)
- proposal_id
- client_id

在sql中有一种方法,即proposal_id只为每个client_id

递增

示例:

ID proposal_id client_id
1 1 1
2 1 2
3 2 1
4 3 1
5 2 2
6 3 2

我知道我可以获得最后一个poposal_id和+1并且我添加新条目...但我不想只是为了获得这个值而执行sql指令...而是我想在sql中使用!< / p>

TKZ 罗伯特

3 个答案:

答案 0 :(得分:1)

据我所知,您希望每个client_id以一个连续方式将proposal_id作为序列。您应该规范化表以分成每个客户端表[棘手且不可取]来执行此操作或编写SELECT

答案 1 :(得分:1)

我认为如果使用innodb(推荐),这就是你想要的,尽管你可以使用myisam简化这个

delimiter ;

drop table if exists customer;
create table customer(
 cust_id int unsigned not null auto_increment primary key,
 name varchar(255) unique not null,
 next_proposal_id smallint unsigned not null default 0
)engine = innodb;

insert into customer (name) values ('c1'),('c2'),('c3');

drop table if exists proposal;
create table proposal(
 cust_id int unsigned not null,
 proposal_id smallint unsigned not null,
 proposal_date datetime not null,
 primary key (cust_id, proposal_id) -- composite clustered primary key
)engine=innodb;

delimiter #

create trigger proposal_before_ins_trig before insert on proposal for each row
begin
  declare new_proposal_id smallint unsigned default 0;

  select next_proposal_id+1 into new_proposal_id from customer 
   where cust_id = new.cust_id;

  update customer set next_proposal_id = new_proposal_id where cust_id = new.cust_id;

  set new.proposal_id = new_proposal_id;
  set new.proposal_date = now();
end#

delimiter ;

insert into proposal (cust_id) values (1),(2),(1),(3),(2),(1),(1),(2);

select * from proposal;
select * from customer;

希望它有所帮助:)

我已经在下面添加了myisam版本以获得良好的衡量标准:

drop table if exists customer;
create table customer(
 cust_id int unsigned not null auto_increment primary key,
 name varchar(255) unique not null
)engine = myisam;

insert into customer (name) values ('c1'),('c2'),('c3');

drop table if exists proposal;
create table proposal(
 cust_id int unsigned not null,
 proposal_id smallint unsigned not null auto_increment,
 proposal_date datetime not null,
 primary key (cust_id, proposal_id) -- composite non clustered primary key
)engine=myisam;

insert into proposal (cust_id,proposal_date) values 
(1,now()),(2,now()),(1,now()),(3,now()),(2,now()),(1,now()),(1,now()),(2,now());

select * from customer;
select * from proposal order by cust_id;

答案 2 :(得分:-2)

我认为您可以设计一个足够复杂的查询来处理这个问题,而不需要任何非SQL代码,但这并不符合您所要求的精神。没有办法创建您要求的特定于字段的增量类型作为表本身的规范。