How to select one row randomly taking into account a weight?

后端 未结 7 2001
一生所求
一生所求 2020-11-29 11:58

I have a table which looks like that:

id: primary key
content: varchar
weight: int

What I want to do is randomly select one row from this t

7条回答
  •  臣服心动
    2020-11-29 12:57

    This works in MSSQL and I am sure that it should be possible to change couple of keywords to make it work in MySQL as well (maybe even nicer):

    SELECT      TOP 1 t.*
    FROM        @Table t
    INNER JOIN (SELECT      t.id, sum(tt.weight) AS cum_weight
                FROM        @Table t
                INNER JOIN  @Table tt ON  tt.id <= t.id
                GROUP BY    t.id) tc
            ON  tc.id = t.id,
               (SELECT  SUM(weight) AS total_weight FROM @Table) tt,
               (SELECT  RAND() AS rnd) r
    WHERE       r.rnd * tt.total_weight <= tc.cum_weight
    ORDER BY    t.id ASC
    

    The idea is to have a cumulative weight for each row (subselect-1), then find the position of the spanned RAND() in this cumulative range.

提交回复
热议问题