I have an InooDB table:
- id - primary key, auto increment
- short_code - varchar(6), unique
- some other columns
The short_code
is always generated in php based on id
.
The problem is that I can't generate the short_code
before inserting a record, because I don't know the id
.
I tried the following:
- insert a record with empty short_code
- get the id of the inserted row with
mysqli_insert_id
, or pdo, whatever - generate the short code based on the id, and update the record with the new short_code
This works, but this is really slow. I have to do an insert and also an update, which is time consuming.
A better idea is to "guess" the id the record I want to insert will have, with
select max(id)+1 from mytable;
(or something similar), generate the short_code, and insert the record. Here I have a SELECT and one INSERT which is actually much better.
My question is:
- Is there a smarter solution for this problem?
- If no, and I go with solution 2 (guessing the next id), how can I make sure that in the time I do the
select max(id)+1 from mytable;
, generate short code, and insert a record, nobody will insert another record, somax(id)=1
doesn't change in meantime?
NOTE!
- I can not generate the short code in a mysql procedure.
- Short code must be generated based on the id.