Auto increment based on two columns?
This might be simple and I'm just having a mental day, but here goes...
I'm trying to accommodate an incremental value in column B, for each unique value of column A. That is, an incremental parcel number for each department:
CREATE TABLE shipments
deptId BIGINT UNSIGNED,
parcelId BIGINT UNSIGNED,
Obviously a normal auto_increment won't work.
I can manually calculate the next available parcel number for a given deptId, when I insert, eg
However, this wouldn't return my new parcelId (which I'd really like it to do, for my application layer). I could do a separate SELECT to get the next available parcelId, and then do an INSERT, but then there's the (slight, but real) possibility of a race condition. So I can't really think of a solution that would accomplish the following:
INSERT INTO shipments(deptId,parcelId)
FROM shipments WHERE deptId=1
- Maintain an incremental value in column B for a specified value in column A
- Upon insert, return the new value of column B
- Avoid race conditions
Hopefully someone will point out the blindingly obvious solution that I've missed...