dongqingcheng2903 2010-05-05 06:30
浏览 164
已采纳

从MySQL表中选择行数百分比的最简单方法?

I have a script that has a GET variable: $_GET['percentage']

I have a MySQL table of data.

Now lets say that there are 100 rows of data in this table.

In pseudo-code:

SELECT data FROM table

Now would it be possible to select $_GET['percentage'] of random data from table?

For example (again in pseudo-code):

$_GET['percentage'] = 10;
SELECT 10% of data from table order by rand()

If this IS possible, how could I do it?

  • 写回答

4条回答 默认 最新

  • dongtuliao6760 2010-05-05 07:03
    关注

    In MySQL, it's probably easiest to do this in two queries. First, get the count of rows in the table:

    SELECT COUNT(*) FROM MyTable;
    

    Then prepare the query to get random rows:

    SELECT ... FROM MyTable ORDER BY RAND() LIMIT ?;
    

    Then execute the prepared query and send the value of the count divided by 10.

    Not every problem needs to be solved by a single query.


    Here's an example PHP script, edited to use the old mysql extension.

    <?php
    
    // Get the total number of rows in the table.
    $sql = "SELECT COUNT(*) FROM Kingdoms";
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
    $rows_in_table = $row[0];
    
    // We only want a portion of the rows, specified by the user
    // choice of percentage.  The count we want is therefore equal
    // to the total number of rows in the table multiplied by the
    // desired percentage.
    $percentage = intval($_GET["percentage"]) / 100.0;
    $count = intval(round($rows_in_table * $percentage));
    
    // LIMIT makes the query return at most the number of rows specified.
    // Sort randomly first (if the table has too many rows this will be slow),
    // then return the first $count rows.
    $sql = "SELECT * FROM Kingdoms ORDER BY RAND() LIMIT {$count}";
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
      print_r($row);
    }
    

    PS: Always be careful when interpolating a variable into an SQL expression. You should force the variable to a known format -- an integer value in this case. Otherwise you risk creating an SQL Injection vulnerability.

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

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?