如何随机的从mysql表中取出一条记录?

时间:2021-07-01 23:24:23

*大家都玩过吧,它上面有个“随机条目”,如果我们本地用的是mysql,也想实现同样的功能,怎么实现这个功能呢? 如何做效率才高呢?


$conn = mysql_connect('127.0.0.1','root','root') or die (mysql_error());
mysql_select_db('test');
mysql_query('SET NAMES UTF8');
$sql = " select count(1) as t from cj_question ";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);

$count = empty($data) ? 0 : intval($data['t']);

if (empty($count))
{
die('表中没有数据');
}

$offset = mt_rand(0,$count-1);

$sql = " select * from cj_question limit $offset,1 ";

$result = mysql_query($sql);

$data = mysql_fetch_assoc($result);
var_dump($data);