其实,从数据库随机获取数据,很简单,只须用到一个rand()函数
select * from table_name order by rand() limit 0,5
下面是一个小实例:
从文章表中随机获取5条数据。
$dblink=mysql_connect("localhost","root","123456")
mysql_query("set names utf8")
mysql_select_db("aixuexi")
$sql="select * from waxx_article order by rand() limit 0,5"
$rs=mysql_query($sql)
while($row=mysql_fetch_array($rs)){
$rows[]=$row
}
if($rows){
foreach($rows as $v){
?>
<div style="width:350pxheight:35pxline-height:35pxborder:1px solid #ccc"><?php echo $v['title']?></div>
<?php
}
}else{
echo "暂无文章"
}
1.随机读取连续多条记录。经过实践,可以随机读取多条连续的数据记录,里头取值的一般都是主键ID来进行最大值、最小值的读取:
SELECT * FROM example_table AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM example_table)-(SELECT MIN(id) FROM example_table))+(SELECT MIN(id) FROM example_table)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 52.随机多条数据。以下两种都是随机读取数据,查询数据速度、随机范围都基本相差不大
SELECT * FROM example_table WHERE id >= ((SELECT MAX(id) FROM example_table)-(SELECT MIN(id) FROM example_table)) * RAND() + (SELECT MIN(id) FROM example_table) LIMIT 5 SELECT * FROM example_table WHERE id>=(SELECT floor(RAND() * ((SELECT MAX(id) FROM example_table)-(SELECT MIN(id) FROM example_table)) + (SELECT MIN(id) FROM example_table))) ORDER BY id LIMIT 5欢迎分享,转载请注明来源:内存溢出
评论列表(0条)