当前位置:首页 > 站长学院 > 建站教程 >

PHPCMSV9高效率的调用随机数据标签的三个方法

作者:齐鲁建站    发布时间:2020-08-11    阅读:
最近建站碰到一个要随机查询数据,最简单的是用order by rand() 来操作,页面多的话效率不高,结合网上的资料,现在给大家介绍一个高效率的方法。下面齐鲁建站小编就来说说PHPCMSV9高效率的调用随机数据标签的三个方法。

如果指定了栏目,一般最简单的做法是

{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_mydemo where status='99' catid in(1,2,3) order by rand()" num="10"}

刚刚说了,这样的效率很低!这里分享一个高效率的随机SQL调用标签。

高效率代码:(以文章模型为例

{pc:get sql="select * from phpcms_mydemo as t1 join (select round(rand() * ((select max(id) from phpcms_mydemo)-(select min(id) from phpcms_mydemo))+(select min(id) from phpcms_mydemo)) 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_mydemo as t1 join (select round(rand() * ((select max(id) from phpcms_mydemo)-(select min(id) from phpcms_mydemo))+(select min(id) from phpcms_mydemo)) 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_mydemo as t1 join (select round(rand() * ((select max(id) from phpcms_mydemo)-(select min(id) from phpcms_mydemo))+(select min(id) from phpcms_mydemo)) 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_mydemo 改为 phpcms_自定义 即可。

QQ客服
QQ客服
陈经理