当前位置:Gxlcms > PHP教程 > mysql随机推荐未关注用户

mysql随机推荐未关注用户

时间:2021-07-01 10:21:17 帮助过:28人阅读

随机推荐10个用户可以用 order by rand(),但数据量大很影响效率
$sql='select uid from member order by rand() limit 10';
或者随机uid,然后从uid里找,eg:

for($i=0;$i<10;$i++){
$rand[]=mt_rand(1,100);
}
$sql="select uid from member where uid in (%s) and uid not in (select focus_uid from member_focus where uid ={$uid} ) limit 10";
$sql = sprintf($sql,implode(',',$rand));

问题是$rand里的uid可能没在表member里,这样就不足10个了,微博是这样的吗?还有其他方案吗?

回复内容:

随机推荐10个用户可以用 order by rand(),但数据量大很影响效率
$sql='select uid from member order by rand() limit 10';
或者随机uid,然后从uid里找,eg:

for($i=0;$i<10;$i++){
$rand[]=mt_rand(1,100);
}
$sql="select uid from member where uid in (%s) and uid not in (select focus_uid from member_focus where uid ={$uid} ) limit 10";
$sql = sprintf($sql,implode(',',$rand));

问题是$rand里的uid可能没在表member里,这样就不足10个了,微博是这样的吗?还有其他方案吗?

可以给某个字段存一个随机数,并且对这个字段做索引,然后查询时产生一个随机数,获取大于这个随机数的若干记录就行了

先取maxid 然后在随机取10个id,查询,判断是否关注,如果缺少,然后再随机取10个,查询,判断是否关注,最后拼凑.

  1. 读取表中数量总量select count(*) from tbl;
  2. 通过程序获取不重复的随机的10个数字,数字范围为0~count(*)-1
  3. 依次执行查询select * from tbl limit num,1;
  4. 记得,把查询出来的数据做缓存.

人气教程排行