随机取记录的两种方法

 

1、
mysql: select * from tablename order by rand() limit 1


//把limit后面的数值改为您想随机抽取的条数,我这里只取一条。

2、

$query= "SELECT count(*) as count FROM recommends";
....

$max_num = $row['count'];//取记录总数
srand((double)microtime()*1000000);//随机数种子
$se_pos = rand(0, $max_num);//随机数范围
$length = 6;//记录条数
if (($max_num - $se_pos) <= $length)
    $se_pos = $max_num - $se_pos; //记录数不足6条的情况

$query = "SELECT * FROM recommendsn limit ".$se_pos.",".$length;


 

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;

标签: SELECT, limit, rand