Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Select a random record

by ncw (Friar)
on Sep 05, 2000 at 00:04 UTC ( [id://31037]=note: print w/replies, xml ) Need Help??


in reply to Select a random record

You could count the number of records using
SELECT count(*) FROM table
Then you could pick a random number from 0..$n-1 - call it $rand and using the 2 paramter form of LIMIT select it, eg
SELECT * FROM table ORDER BY id LIMIT $rand, 1
This should be very quick and efficient. You should ORDER BY the primary key probably for maximum speed (where it says id above).

This method has the advantage that it will work with a WHERE clause on the the SELECTs), eg WHERE setup=1 or something like that

This two parameter LIMIT might be MySQL specific I don't know (it doesn't say it is in the manual though)

Update: I tried this on a large MySQL table (with 100ish columns and 500,000ish rows). Leaving out ORDER BY made only a very small difference. The first SQL statement was instant. The second took 8 seconds varying by $rand so maybe it is doing a full table scan here :-(

Replies are listed 'Best First'.
RE: Re: Select a random record
by elwarren (Priest) on Sep 05, 2000 at 02:48 UTC
    Order by is only going to add overhead. If he wants a random record it will be faster to return them in their stored order.
RE: Re: Select a random record
by Maclir (Curate) on Sep 05, 2000 at 00:57 UTC
    Looking through my Informix SQL reference manual, there is no reference to the "LIMIT" parameter.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://31037]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2024-04-25 09:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found