宜昌本地软件开发与弱电工程服务商
项目咨询 · 快速响应

[php]php随机从数据库中随机读取n条不重复记录

2016-10-13 00:16:48 点击量:15 标签: 收藏本文

最近需要从数据库中随机读取n条不重复记录,发现网上好多都是用SELECT * FROM test ORDER BY rand() LIMIT 0,n
当数据库量大的时候排序好像费不少时间!
于是就自己写了一个,希望高手指点一二!

test的结构

id  test
-----
1  asdfasfdasdf
2  sdfsdfsdf
...   ...

  1. <?php 
  2.  
  3. //假设数据库已经连接了 
  4.  
  5. $n = 10;  //随机显示的记录数 
  6. $results = $result = array();  //记录结果的数组 
  7.  
  8. $rowNum = mysql_result(mysql_query("SELECT COUNT(*) AS cnt FROM test"), 0, 0); 
  9.  
  10. if($rowNum < 50) { //数据量小的话,这样反而可以提高效率,当然50可以随便改 
  11.  
  12. $query = mysql_query("SELECT * FROM test ORDER BY rand() LIMIT 0,$n"); 
  13. while($result = mysql_fetch_array($query)) { 
  14. $results[$result['id']] = $result; 
  15. } 
  16.  
  17. } else { 
  18.  
  19. //随机的范围 
  20. $maxNum = mysql_result(mysql_query("SELECT MAX(vid) AS cnt FROM test"), 0, 0); 
  21. $minNum = 1; 
  22. $midNUm = intval($maxNum / 2); 
  23.  
  24. //随机的id 
  25. $randId = null; 
  26.  
  27. //已存在的id集合 格式为 xx,xx,xx,xx 
  28. $existId = ''; 
  29. $comma = ''; 
  30.  
  31. $i = 0; 
  32. while($i < $n && $minNum <= $maxNum) { 
  33.  
  34. $query = ''; 
  35. //再查询中剔除已存在的id 
  36. $existIdExp = $existId ? "AND id NOT IN ($existId)" : ''; 
  37. do{ 
  38. mt_srand((float)microtime() * 1000000); 
  39. $randId = mt_rand($minNum, $maxNum); 
  40. }while(array_key_exists($randId, $results));   //如果产生id已经存在,继续随机 
  41. if($randId <= $midNUm) { 
  42. $query = mysql_query("SELECT * FROM test WHERE id <= $randId $existIdExp LIMIT 0,1"); 
  43. if($result = mysql_fetch_array($query)) { //找到记录记录内容,重新随机 
  44.  
  45. $results[$result['id']] = $result; 
  46. $existId .= $comma.$result['id']; 
  47. $comma = ','; 
  48. $i++; 
  49. } else { //没有找到记录,缩小随机的范围 
  50. $minNum++; 
  51. } 
  52. } else { 
  53. $query = mysql_query("SELECT * FROM test WHERE id >= $randId $existIdExp LIMIT 0,1"); 
  54. if($result = mysql_fetch_array($query)) { //找到记录记录内容,重新随机 
  55. $results[$result['id']] = $result; 
  56. $existId .= $comma.$result['id']; 
  57. $comma = ','; 
  58. $i++; 
  59. } else { //没有找到记录,缩小随机的范围 
  60. $maxNum--; 
  61. } 
  62. } 
  63. } 
  64. } 
  65. var_dump($results); 
  66.  
  67. ?>