MySQL select 10 random rows from 600K rows fast

后端 未结 26 2931
粉色の甜心
粉色の甜心 2020-11-21 05:06

How can I best write a query that selects 10 rows randomly from a total of 600k?

26条回答
  •  独厮守ぢ
    2020-11-21 05:27

    I am getting fast queries (around 0.5 seconds) with a slow cpu, selecting 10 random rows in a 400K registers MySQL database non-cached 2Gb size. See here my code: Fast selection of random rows in MySQL

    $time= microtime_float();
    
    $sql='SELECT COUNT(*) FROM pages';
    $rquery= BD_Ejecutar($sql);
    list($num_records)=mysql_fetch_row($rquery);
    mysql_free_result($rquery);
    
    $sql="SELECT id FROM pages WHERE RAND()*$num_records<20
       ORDER BY RAND() LIMIT 0,10";
    $rquery= BD_Ejecutar($sql);
    while(list($id)=mysql_fetch_row($rquery)){
        if($id_in) $id_in.=",$id";
        else $id_in="$id";
    }
    mysql_free_result($rquery);
    
    $sql="SELECT id,url FROM pages WHERE id IN($id_in)";
    $rquery= BD_Ejecutar($sql);
    while(list($id,$url)=mysql_fetch_row($rquery)){
        logger("$id, $url",1);
    }
    mysql_free_result($rquery);
    
    $time= microtime_float()-$time;
    
    logger("num_records=$num_records",1);
    logger("$id_in",1);
    logger("Time elapsed: $time segundos",1);
    

提交回复
热议问题