sql - randomly generating unique number between 1-999 for primary key in table -
i have problem i'm not sure how solve elegantly.
background information
i have table of widgets. each widget assigned id range of numbers, let's between 1-999. values of 1-999 saved in database "lower_range" , "upper_range" in table called "config". when user requests create new widget using web app, need able following:
- generate random number between 1 , 999 using lua's math.random function or maybe random number generator in sqlite (so far, in tests, lua's math.random returns same value...but that's different issue)
- do select statement see if there widget number assigned...
- if not, create new widget.
- otherwise repeat process until number not in use.
problem
the problem see above logic two-fold:
- the algorithm can potentially take long time because have keep searching until find unique value.
- how prevent simultaneous requests new widget numbers generating same value?
any suggestions appreciated. thanks
generate random numbers ahead of time , store them in table; make sure numbers unique. when need next number, check how many have been assigned , next number table. so, instead of
- generate number between 1-999
- check if it's assigned
- generate new number, , on.
do this:
- generate array of 999 elements have values 1-999 in random order
- your
getnextid
function becomesreturn ids[currentmaxid+1]
to manage simultaneous requests, need have resource generates proper sequence. easiest use key in widget table index in ids
array. so, add record widgets
table first, key , generate widget id using ids[key]
.
Comments
Post a Comment