如何从MySQL中的表中选择随机行

时间:2014-02-11 04:06:37

标签: php mysql

我正在创建一个涉及从mysql数据库中获取一些问题的项目。例如,如果我的数据库中有200个问题,我想随机选择20个问题,这样任何一个问题都不会重复两次。也就是说,我希望能够在每次用户尝试获取要回答的问题列表时,从200个问题中获得20个不同问题的数组。我将非常感谢你的帮助。

4 个答案:

答案 0 :(得分:2)

   SELECT * FROM questions ORDER BY RAND() LIMIT 20;

PS ^这种方法不适用于非常大的表

答案 1 :(得分:0)

使用Google查找创建包含20个唯一数字的数组的函数,其中包含最小值和最大值。使用此数组准备SQL查询,例如:

expression IN (value1, value2, .... value_n);

有关SQL here的更多信息。

可能的数组填充函数here too

答案 2 :(得分:0)

如果你知道表格中有多少行,你可以使用LIMIT。有限制你指定一个随机偏移;语法:LIMIT offset,count。例如:

<?php
$totalRows = 200; // get his value dynamically or whatever...
$limit = 2; // num of rows to select
$rand = mt_rand(0,$totalRows-$limit-1);
$query = 'SELECT * FROM `table` LIMIT '.$rand.','.$limit;
// execute query
?>

这对大表来说应该是安全的,但它会选择相邻的行。然后,您可以通过array_randshuffle混合结果集:

<?php
// ... continued
$resultSet = $pdoStm->fetchAll();
$randResultKeys = array_rand($resultSet,$limit); // using array_rand
shuffle($resultSet); // or using shuffle
?>

答案 3 :(得分:0)

假设您的数据库中有连续的数字问题,您只需要一个包含20个随机数的列表。假设您希望用户能够进行多个测试并获得另外20个问题而无需重复,那么您可以从200个数字的随机数组开始,并从该组中顺序选择20个块,即

$startQuestion=1;
$maxQuestion=200;
$numberlist= range(1,$maxQuestion);
shuffle($numberlist);

function getQuestionSet( $noOfQuestions )
{
  global $numberlist, $maxQuestion, $startQuestion; 
  $start= $startQuestion;
  if( ($startQuestion+$noOfQuestions) > $maxQuestion)
  {
    echo "shuffle...\n";
    shuffle($numberlist);
    $startQuestion=1;
  }else
    $startQuestion+= $noOfQuestions;

  return array_slice($numberlist,$start,$noOfQuestions);
}

// debug...
for($i=0; $i<42; $i++)
{
  $questionset= getQuestionSet( 20 );
  foreach( $questionset as $num )
    echo $num." ";
  echo "\n";
}

然后使用$ questionset来检索您的问题

相关问题