Page 1 of 1

Want a random code

Posted: Fri Jul 06, 2007 1:21 pm
by hesham2012
i have a database table contains many numbers from 1 : 200 a want to generate a random code between 1 : 200 but this code must be different than others in database !how come?

Posted: Fri Jul 06, 2007 1:30 pm
by superdezign
How come? Not sure. It's your idea.

You want the number to be IN the database, or you just want to make a random number, then check if it's there?

Posted: Fri Jul 06, 2007 3:16 pm
by Ambush Commander
There are several ways to go about this, ranging in complexity and performance.

One simple, easy way of implementing this is simply generating a number from 1 to 200 and then doing it again if you get a unique key violation. Of course, you run a very high risk of collision once you start generating an appreciable amount of numbers.

You could also select all rows from the database, invert it, and generate a random key from that set.

I wonder why 200 though: that's very small, and it'll be filled up in no time.

Posted: Fri Jul 06, 2007 7:47 pm
by nathanr
i don't really understand but.. you could always use the mysql solution to return 1 row from the table

SELECT * FROM tablename ORDER BY RAND() LIMIT 1

I'm sure it's rand?? although check the mysql manual - if indeed this is what you mean

Posted: Sun Jul 08, 2007 9:37 am
by Ambush Commander
nathanr, I'm fairly certain your query works, but it specifically selects a row that does exist: this guy wants the converse.