Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mySQL select random with probability

Tags:

sql

mysql

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.

like image 565
Wintermute Avatar asked Jan 09 '12 17:01

Wintermute


1 Answers

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
like image 181
Eugen Rieck Avatar answered Oct 10 '22 05:10

Eugen Rieck