Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think this is what you want if using innodb (recommended) although you can simplify this with myisam </p> <pre><code>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; </code></pre> <p>hope it helps :)</p> <p>i've added the myisam version below for good measure:</p> <pre><code>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; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload