We have table MySql 5.5:
CREATE TABLE IF NOT EXISTS `invoices` (
`id` varchar(36) NOT NULL,
`client_id` smallint(4) NOT NULL,
`invoice_number` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `client_id_2` (`client_id`,`invoice_number`),
KEY `client_id` (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
We insert data into that table like this:
INSERT INTO `invoices` ( `id` , `client_id` , `invoice_number` )
VALUES (
UUID(),
10 ,
( SELECT (MAX(`invoice_number`) +1) as next_invoice_number FROM `invoices` WHERE `client_id` = 10 )
);
"10" is client_id
value.
It works but, it has bad concurrency. How can I have working solution, which has good concurrency?
Composite-primary-key auto increment is not a solution. We need autoincrement per client_id value. Composite-primary-key auto increment gives autoincrement all over table not per client_id column value.