I am recently in the process of moving from oracle to mysql and would like some advice if how i am implementing something similar to sequences in mysql is a good way.

Essentially how i am currently going to implement it is by having a separate table in mysql for each sequence in oracle and have a single column which represents the last_number and increment this column when ever i insert a new row, that's one way another way i could go about doing it is by creating a single table with several rows representing each sequence and increment each row separately whenever i do an insert.

Another simpler way of doing it i could just do a select max()+1 on the relevant column when inserting data.

I'm basically thinking of switching to the select max()+1 option as it seems simpler to implement, but i would like to get some advice on what you think would be the best way of doing it out of these options, and if there is any pitfalls that i am currently not aware of when using select max()+1.

Also the reason im am not using auto_increment and the function last_insert_id() is i want to follow the ansi standard.

Thanks.

有帮助吗?

解决方案 2

There is a read consistency problem, in that two sessions both running ...

insert into ... select max(..)+1 from ...

... at the same time both see the same value of max(...), hence they both try to insert the same new value.

You have the same problem with your table of maxima method, and you have to use a locking mechanism to avoid multiple session reading the same value. This leads to a concurrency problem where inserts to the table are serialised.

其他提示

First of all: The max()+1 version is NOT guaranteed to give you a sequence, if you use transactions in a high isolation level.

The way we typically use sequences (if we can't avoid them) is to create a table with an AUTO_INCREMENT value, INSERT INTO it, SELECT last_insert_id(), DELETE FROM table WHERE field<$LASTINSERTID. This is ofcourse done in a stored procedure.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top