I have a database table which has a compound primary key (id_a, id_b). That’s not what they’re actually called but I am simplifying for this question. id_a is a foreign key and id_b is just an integer, “sequence number” so to speak. I cannot just make id_b auto_incrementing because it is not allowed for the InnoDB storage engine (as it is not the first field in the compound key).
I would like to make it so that these objects can be “grouped” with id_a, so for example:
id_a id_b
----------------
1 1
1 2
2 1
2 2
2 3
and the result of inserting a row with (id_a=1) should automatically set id_b=3. I would like to avoid using database locks, especially since there is no need to lock the entire table when concurrent inserts with different id_a should totally be allowed.
I am accessing this database through Python via SQLAlchemy (using the ORM), although I suspect this question can be answered agnostically with regards to the client side (pure MySQL).
SELECT coalesce(max(ID_B),0)+1FROM yourTable
WHERE ID_A = '1'
However, without the locking, you run the risk of getting duplicate ID_B values, so you’d have to handle duplicate key errors on the insert statements. Either “Retry” within code automatically for a set number of times or error and force user to try again.