Home > Backend Development > PHP Tutorial > mysql随机推荐未关注用户

mysql随机推荐未关注用户

WBOY
Release: 2016-06-06 20:44:24
Original
1149 people have browsed it

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

<code class="lang-php">for($i=0;$i</code>
Copy after login
Copy after login

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

回复内容:

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

<code class="lang-php">for($i=0;$i</code>
Copy after login
Copy after login

问题是$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. 记得,把查询出来的数据做缓存.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template