分享一个高效率的随机调用数据的标签

发表于2014-07-30 15:46:30来源于PHPCMS官方论坛

次点击[] [] [] [打印] [关闭窗口] [评论]

欢迎大家加入创想工作室QQ群 网络瘫痪上不了网?电脑出故障?找破解软件?加入创想工作室QQ群,向大神求助,一步解决问题!QQ群号码:326338868[点此获取更多QQ群]
今天我们碰到一个要随机查询数据,一开始我们可能想到最简单的order by rand() 来操作,如果生成的页面很多,效率不敢恭维啊,很多人在QQ问我怎么做才能提高效率,结合了网上的资料,现提供代码给各位鞋童参考一下哈。
 
如果指定了栏目,一般最简单的做法是
{pc:content action="lists" catid="2" num="10" order="rand()"}
{loop $data $r}
<li><a href="{$r[url]}" target="_blank"{title_style($r[style])}>{$r[title]}</a> {date('Y-m-d H:i:s',$r[inputtime])}</li>
{/loop}
{/pc}
或者
{pc:get sql="select * from phpcms_news where status='99' catid in(1,2,3) order by rand()" num="10"}
刚刚说了,这样的效率很低!这里分享一个高效率的随机SQL调用标签。
 
高效率代码:(以文章模型为例)
{pc:get sql="select * from phpcms_news as t1 join (select round(rand() * ((select max(id) from phpcms_news)-(select min(id) from phpcms_news))+(select min(id) from phpcms_news)) as id) as t2  where t1.id >= t2.id and t1.status=99 order by t1.id" num="10"}
如果要指定栏目,则在 “order by t1.id” 前面加上 and t1.catid in(1,2,3)
{pc:get sql="select * from phpcms_news as t1 join (select round(rand() * ((select max(id) from phpcms_news)-(select min(id) from phpcms_news))+(select min(id) from phpcms_news)) as id) as t2  where t1.id >= t2.id and t1.status=99 and t1.catid in(1,2,3) order by t1.id" num="10"}
如果需要调用当前栏目(包含子栏目),则
{php $bcatid = $CATEGORYS[$catid]['arrchildid'];}
{pc:get sql="select * from phpcms_news as t1 join (select round(rand() * ((select max(id) from phpcms_news)-(select min(id) from phpcms_news))+(select min(id) from phpcms_news)) as id) as t2  where t1.id >= t2.id and t1.status=99 and t1.catid in($bcatid) order by t1.id" num="10"}
 
注意这里的数据库前缀 phpcms_ 改为你当前的数据库前缀。
 
如果需要随机调用下载模型的,则把 phpcms_news 改为 phpcms_download 即可。

© copyright 2002-2024, 22BA.COM All Rights Reserved

网站备案号:粤ICP备19114910号

ChuangXiang Design Studio - WebDesign & Internet Marketing

关于我们业务范围联系我们开心一刻网站地图

QQ群一:326338868QQ群二:78712271

QQ群三:193078177

邮箱:news@22ba.com

地址:深圳市福田区金田路现代国际大厦2606