Home >Backend Development >PHP Tutorial >从MySQL数据库表中取出随机数据的代码_php技巧

从MySQL数据库表中取出随机数据的代码_php技巧

WBOY
WBOYOriginal
2016-05-17 09:39:05969browse

MySQL 如何从表中取出随机数据 
以前在群里讨论过这个问题,比较的有意思.mysql的语法真好玩.

他们原来都想用PHP的实现随机,但取出多条好像要进行两次以上查询.

翻了手册,找到了下面这个语句,可以完成任务了

SELECT * FROM table_name ORDER BY rand() LIMIT 5;

rand在手册里是这么说的:
RAND() 
RAND(N) 
返回在范围0到1.0内的随机浮点值。如果一个整数参数N被指定,它被用作种子值。 
mysql> select RAND();
        -> 0.5925
mysql> select RAND(20);
        -> 0.1811
mysql> select RAND(20);
        -> 0.1811
mysql> select RAND();
        -> 0.2079
mysql> select RAND();
        -> 0.7888
你不能在一个ORDER BY子句用RAND()值使用列,因为ORDER BY将重复计算列多次。然而在MySQL3.23中,你可以做: SELECT * FROM table_name ORDER BY RAND(),这是有利于得到一个来自SELECT * FROM table1,table2 WHERE a=b AND c
但我试了一下,8千条记录的表,执行一次需要0.08 sec,.慢了些

后来请教了google,得到如下代码

SELECT * 
 FROM table_name AS r1 JOIN 
    (SELECT ROUND(RAND() * 
           (SELECT MAX(id) 
            FROM table_name)) AS id) 
    AS r2 
WHERE r1.id >= r2.id 
ORDER BY r1.id ASC 
LIMIT 5;

执行效率需要0.02 sec.可惜的是,只有mysql 4.1.*以上才支持这样的子查询. 

以下是php代码:

<&#63;
//数据库连接就不写在这里面了
$s = isset( $_GET['s'] )&#63;$_GET['s']:0;
$e = isset( $_GET['e'])&#63;$_GET['e']:50;
$count =85000;
if( $s < $count )
{
 $sql = "select * from 表前缀_info where isget =0 order by id desc limit $s,$e ";
 $query = mysql_query( $sql );
 while( $rs = mysql_fetch_array( $query ) )
 {
 $id = $rs['id'];
 $sss = $rs['sss'];
 $typeid = $rs['typeid'];
 $isget = $rs['isget'];
 $sql = "insert into 表前缀_info_bak (id,表前缀,typeid,isget) values('$id','$sss','$typeid','$isget')";
 mysql_query( $sql ) ;
 echo $sql;
 //exit;
 $sqlu = "update 表前缀_info set isget=1 where id =".$rs['id'];
 mysql_query( $sqlu );
 }
 echo '<meta http-equiv="refresh" content="0;url=rand.php&#63;s='.($s+50).'&e=50">正在处理数据,当前为'.$s.'条......';
}
else
{
 echo '完成所有数据处理 <a href=rand.php>再随机排序一次</a>';
}
&#63;>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn