Since you specifically mention wanting a "unique but random" number, I assume the other replies about using an "autoincrement" field would be inappropriate as well, since these are not at all random.
A solution I've used in the past (admittedly a kluge with a minor limitation) is to generate a randomized list of numbers first, store that list in a separate table, then select from it sequentially as needed. Include a "status" field along with the randomized numeric value field, and hand out random but unique numbers like this:
The "for update" in the select is supposed to keep some other query from fetching the same row until the update has been done.my ($pin) = $dbh->selectrow_array( "select pin_value from pins where s +tatus is null limit 1 for update" ); $dbh->do( "update pins set status='used' where pin_value=$pin" );
The limitation, of course, is that you need to make sure the pins table doesn't run out of available rows. It's easy enough to solve with a cron job or something that checks the number of unused rows at regular intervals and adds more whenever it gets too close to zero. In this case, the "add_pins" process just needs to make sure that only adds numbers that haven't been used yet, and that's pretty easy using a hash. For that matter, it's not hard to make sure your initial sequence of random numbers is big enough.
This approach is really nice if you want to put any sort of constraint on the range of possible numeric values being handed out (e.g. they should all be 6-digit, not begin with 0, not contain "666", or whatever).
In reply to Re: DBI Insert Unique Customer ID
by graff
in thread DBI Insert Unique Customer ID
by kalchas
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |