I have a MySQL database which contains a table of users. The primary key of the table is 'userid', which is set to be an auto increment field.
What I'd like to do is when I insert a new user into the table is to use the same value that the auto increment is creating in the 'userid' field in a different field, 'default_assignment'.
e.g.
I'd like a statement like this:
INSERT INTO users ('username','default_assignment') VALUES ('barry', value_of_auto_increment_field())
so I create user 'Barry', the 'userid' is generated as being 16 (for example), but I also want the 'default_assignment' to have the same value of 16.
Is there any way to achieve this please?
Thanks!
Update:
Thanks for the replies. The default_assignment field isn't redundant. The default_assigment can reference any user within the users table. When creating a user I already have a form that allows a selection of another user as the default_assignment, however there are cases where it needs to be set to the same user, hence my question.
Update:
Ok, I've tried out the update triggers suggestion but still can't get this to work. Here's the trigger I've created:
CREATE TRIGGER default_assignment_self BEFORE INSERT ON `users`
FOR EACH ROW BEGIN
SET NEW.default_assignment = NEW.userid;
END;
When inserting a new user however the default_assignment is always set to 0.
If I manually set the userid then the default_assignment does get set to the userid.
Therefore the auto assignment generation process clearly happens after the trigger takes effect.
I tested the above trigger idea with 10 concurrent threads doing inserts and I got over 1000 cases of 2 or 3 duplicates after ~25k inserted.
I used 10 of:
And ran the last query to watch for duplicates
example output: '3', '4217' '3', '13491' '2', '10037' '2', '14658' '2', '5080' '2', '14201' ...
Note 'LOCK IN SHARE MODE' didn't change anything. With and without gave duplicates at about the same rate. It seems that MySQL AUTO_INCREMENT doesn't work like Postgres' next_val() and is NOT concurrency safe.
You can do this reliably using a simple subquery:
I know this post is from 2010, but I couldn't find a good solution. I've solved this by creating a separate table that holds the counters. When I need to generate an unique identifier for a column I just call a Stored proc:
The 'for update' statement locks the row in the counters table. This avoids duplicates being made by multiple threads.
there's no need to create another table, and max() will have problems acording to the auto_increment value of the table, do this:
I declare the next_id variable because usually it will be used in some other way(*), but you could do straight new.field=(select ...)
The only I found that would solve this problem without an extra table would be to calculate self the next number and put that in the fields required.