dongmu5815 2015-12-01 03:24
浏览 51
已采纳

如何回应数据库中的随机行?

I have a database table with about 160 million rows in it.

The table has two columns: id and listing.

I simply need to used PHP to display 1000 random rows from the listing column and put them into <span> tags. Like this:

<span>Row 1</span>
<span>Row 2</span>
<span>Row 3</span>

I've been trying to do it with ORDER BY RAND() but that takes so long to load on such a large database and I haven't been able to find any other solutions.

I'm hoping that there is a fast/easy way to do this. I can't imagine that it'd be impossible to simply echo 1000 random rows... Thanks!

  • 写回答

5条回答 默认 最新

  • dov11020 2015-12-01 04:27
    关注

    ORDER BY RAND() is a mysql function working fine with small databases, but if you run anything larger then 10k rows, you should build functions inside your program instead of using mysql premade functions or organise your data in special manners.

    My suggestion: keep your mysql data indexed by auto increment id, or add other incremental and unique row.

    Then build a select function:

    <?php
    //get total number of rows
    $result = mysql_query('SELECT `id` FROM `table_name`', $link); 
    $num_rows = mysql_num_rows($result); 
    
    $randomlySelected = [];
    
    for( $a = 0; $a < 1000; $a ++ ){
    
            $randomlySelected[$a] = rand(1,$num_rows);
    
    }
    
    //then select data by random ids
    $where = "";
    
    $control = 0;
    foreach($randomlySelected as $key => $selectedID){
    
        if($control == 0){
    
            $where .= "`id` = '". $selectedID ."' ";
    
        } else {
    
            $where .= "OR `id` = '". $selectedID ."'";
    
        }
        $control ++;
    }
    
    
    $final_query = "SELECT * FROM `table_name` WHERE ". $where .";";
    $final_results = mysql_query($final_query);    
    
    ?>
    

    If some of your incremental IDs out of that 160 million database are missing, then you can easily add a function to add another random IDs (a while loop probably) if an array of randomly selected ids consists of less then required.

    Let me know if you need some further help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器