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

Rob*_*Rob 4 php mysql

我有一个具有GET变量的脚本: $_GET['percentage']

我有一个MySQL数据表.

现在让我们说这个表中有100行数据.

在伪代码中:

SELECT data FROM table

现在可以$_GET['percentage']从表中选择随机数据吗?

例如(再次使用伪代码):

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

如果这是可能的,我怎么能这样做?

Bil*_*win 8

在MySQL中,在两个查询中执行此操作可能最容易.首先,获取表中的行数:

SELECT COUNT(*) FROM MyTable;
Run Code Online (Sandbox Code Playgroud)

然后准备查询以获取随机行:

SELECT ... FROM MyTable ORDER BY RAND() LIMIT ?;
Run Code Online (Sandbox Code Playgroud)

然后执行准备好的查询并发送计数值除以10.

并非每个问题都需要通过单个查询来解决.


这是一个示例PHP脚本,编辑后使用旧的mysql扩展.

<?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);
}
Run Code Online (Sandbox Code Playgroud)

PS:将变量插入到SQL表达式时要小心.您应该将变量强制为已知格式 - 在这种情况下为整数值.否则,您可能会创建SQL注入漏洞.