quick selection of a random row from a large table in mysql

前端 未结 24 1734
旧时难觅i
旧时难觅i 2020-11-22 09:30

What is a fast way to select a random row from a large mysql table?

I\'m working in php, but I\'m interested in any solution even if it\'s in another language.

24条回答
  •  抹茶落季
    2020-11-22 09:55

    Create a Function to do this most likely the best answer and most fastest answer here!

    Pros - Works even with Gaps and extremely fast.

    0){
           return $fetch_$data;
          }else{
           rando('','',$max); // Start Over the results returned nothing
          }
       }else{
         if($max != '0'){
            $irand = rand(0,$max); 
            rando('s1',$irand,$max); // Start rando with new random ID to fetch
         }else{
    
            $query = mysqli_query($sqlConnect, "SELECT `id` FROM `yourtable` ORDER BY `id` DESC LIMIT 0,1");
            $fetched_data = mysqli_fetch_assoc($query);
            $max = $fetched_data['id'];
            $irand = rand(1,$max);
            rando('s1',$irand,$max); // Runs rando against the random ID we have selected if data exist will return
         }
       }
     }
    
     $your_data = rando(); // Returns listing data for a random entry as a ASSOC ARRAY
    ?>
    

    Please keep in mind this code as not been tested but is a working concept to return random entries even with gaps.. As long as the gaps are not huge enough to cause a load time issue.

提交回复
热议问题