Ok, let me explain the scenario. I have a "orders" table with a auto incr key "orderno" in it. The table has a field "orderdate" also. What I want is a formatted order no. (orderno_formatted) in following style YYYYNUMBER i.e. date of order plus a unique no. and here is the twist. If no order is present for year 2010, "orderno_formatted" should be 20101 i.e. year of order and 1 and then 20102, 20103 etc.
next year in 2011, the (orderno_formatted) should be like 20111, 20112
so what is the best way to achieve this. I know, I can search for max no. in a column but it may开发者_JAVA技巧 be possible, that many users are accessing the site so If a get a max no and save it, meanwhile another user may get the same number.
clear?
any help will be appreciated.
Regards,
I suggest you create a separate sequence table with fields year
and sequence
. You then do:
SELECT sequence FROM year_sequence WHERE year = 2010 FOR UPDATE
This locks the table so that any consecutive selects on the same row will wait for the current transaction to commit (remember to begin a transaction before running SELECT ... FOR UPDATE if your autocommit is enabled).
After this you increment the sequence number you read by one, and push it back with:
UPDATE year_sequence SET sequence = sequence + 1 WHERE year = 2010
Alternatively if the first query did not read any rows, you'll insert a new row with sequence of 1. Then you commit the changes with COMMIT
.
Now you got a sequence number you can use to insert to the another table, that is guaranteed to be unique for that year and there will be no conflicts as long as you remember to use this method anywhere you need to get the next sequence number.
Another way would be to start a transaction, and first run an UPDATE that increments the sequence value by 1, and in the same transaction after the update read the new value, and only after that commit the transaction. That also ensures that the value you read will always be unique, as other transactions will wait until after you read the new value.
If your unique number is 32bit lenght then you can year bits for example at the end of this value, then you have 48bit lenght unique value.
精彩评论