Let's say I've got a database table with an integer field - call it "flavour", and the values of that field can only be the numbers 1 to 10.
Is there a way to select a single random row from the database, with a 20% chance it will be flavour six, a 30% chance it will be flavour two, and a 50% chance it will be flavour one?
Apologies for the late response - many thanks for the help. Eugen's answer seems to best encompass what I need; I'm aware of the dangers of ORDER BY rand(), but the application I'm writing won't operate on a large data source, or have to support many concurrent users. So I'll go with it and accept the performance hit.
SELECT
IF(@rnd<0.5,1,IF(@rnd<0.8,2,6)) AS rndflavour
FROM
(SELECT @rnd:=rand()) AS rndinit;
Gives you the flavour with the requested probabilities.
SELECT * FROM tablename ORDER BY rand() LIMIT 1
gives you a single random row. Now we put it together:
SELECT
tablename.*
FROM
tablename
INNER JOIN (
SELECT
IF(@rnd<0.5,1,IF(@rnd<0.8,2,6)) AS rndflavour
FROM
(SELECT @rnd:=rand()) AS rndinit
) AS rndview ON rndview.rndflavour=tablename.flavour
ORDER BY rand()
LIMIT 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With