Jan 18, 2001, 1:18 AM
Post #3 of 7
If you actually just need to retrieve one row, there's no need to read the whole database not to mention it'll murder your server memory if it's a large database. (All of this assumes that you're using DBI)
Simple 2-step process:
First, get the total count of records by using the COUNT statement:
(Of course, you should add error checking to those statements)
my $query = $DBI->prepare(SELECT COUNT(*) FROM tablename);
my ($total) = $query->fetchrow_array;
Next, get a random number from the first to last number in the total and use the LIMIT statement:
$rec now contains a hash reference of a single, random record.
my $offset = int rand $total;
my $query = $DBI->prepare ( "SELECT * FROM tablename LIMIT $offset, 1");
$query->execute() or die $DBI::errstr;
my $rec = $query->fetchrow_hashref;
Hope this helps!