我一直在阅读有关通过 MYSQL 和 PHP 获取随机行的速度问题,并且想知道如何改进我的代码以提高速度。
我的数据库中有一个名为“banners”的表中的横幅信息,我想显示与页面上的位置相关的随机横幅,并为该横幅的 view_count 添加 +1。我的方法有效,但是对于每个页面加载时都会发生这种情况的繁忙网站,可以提高速度吗?谢谢
/* Get banners for position 1 then choose a random one to display */
$banners = mysql_query("SELECT id,title,banner_url,destination FROM ".TBL_BANNERS." WHERE position = '1' AND status = '1'");
$banner_count = mysql_num_rows($banners) - 1;
$rand_offset = mt_rand(0,$banner_count);
$result = mysql_query("SELECT id,title,banner_url,destination FROM ".TBL_BANNERS." LIMIT $rand_offset, 1 ");
$banner_id = mysql_result($result,0,"id");
$banner_title = mysql_result($result,0,"title");
$banner_url = mysql_result($result,0,"banner_url");
$banner_dest = mysql_result($result,0,"destination");
/* Add view to this banner */
$database->addViewToBanner($banner_id);
最后一个函数使用查询:
"UPDATE banners SET view_count = view_count+1 WHERE id = '$banner_id'"
我还需要说的是,“banners”表中的记录在任何时候都可能不会超过 100 条,但 ID 中会有漏洞。 ID 可能会增加到 200 个,但其中只有一半仍然存在。
最佳答案
在 php 中生成一个随机数并将其钻入 PK
SQL 是
SELECT id,title,banner_url,destination
FROM TBL_BANNERS
WHERE id = $rand_offset
如果错过了,请再次运行。这可以非常有效地查找一行,这比使用限制/偏移处理更好
关于php - 优化我的随机行获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8607201/