mysql order by rand() performance issue and solution

前端 未结 4 863
旧时难觅i
旧时难觅i 2020-12-06 12:39

i was using order by rand() to generate random rows from database without any issue but i reaalised that as the database size increase this rand() causes heavy load on serve

4条回答
  •  萌比男神i
    2020-12-06 13:36

    Use your DB to find the max value from the table, generate a random number less than or equal to that value, grab the first row in which the id is greater than or equal to your random number. No PHP necessary.

    SELECT items
    FROM tablea
    WHERE status = '0' and
          id >= FLOOR(1 + RAND() * (SELECT MAX(id) FROM tablea))
    LIMIT 1
    

提交回复
热议问题