List:General Discussion« Previous MessageNext Message »
From:jingram Date:March 15 2000 8:09pm
Subject:Re: 7 Digit Random Number Generator
View as plain text  

> I very new to mySQL, I am looking for a a way to have the database
> generate a 7 digit id number that is used to reference each entry. Any
> Suggestions?

OK, here's why you shouldn't do this:  You're obviously looking for a
primary key for each record, which must be unique.  Whenever you get a
random number, you're not guaranteeing a unique number unless you first
make sure that number doesn't already exist.  This would require maybe a
subselect (which you can't do in MySQL) or some sort of looping thing that
generates and checks, generates and checks, until it finds one that's not
taken.  Man, is this dumb or what?  What you should do is make it an
auto-increment primary key and then pad it to seven digits in your selects.
Or if you really want a random 7 digit number to be your primary key, you
could probably have Perl do it for you.  But you'll still have that problem
of uniqueness, which will tear you up when you try to code it.  Trust me on
this:  auto_increment the primary key and pad it for display.

Out of curiosity, I was wondering if MySQL could generate a random 7 digit
number.  The quick and easy that I found was this, which *usually* comes up
with a 7 digit number but not always.  I'm sure somebody could tweak it to
always come up with 7, at which time you can refer to my previous comment
about NOT doing it.

select round(rand() * 10000000);

So that's that.

John Ingram

7 Digit Random Number GeneratorJustin15 Mar
  • RE: 7 Digit Random Number GeneratorDaevid Vincent16 Mar
Re: 7 Digit Random Number Generatorjingram15 Mar
RE: 7 Digit Random Number Generatorjingram16 Mar