【发布时间】:2012-06-17 14:18:49
【问题描述】:
我有一个运行 #-tag 趋势的测试页面,该页面存储在我的数据库中。该页面在显示内容之前需要很长时间(最多 2 分钟)加载,该页面只有一个功能使用了
网址:http://www.sudanesetweeps.com/trendingtopics.php
如何调整语句以缩短页面加载时间?
这是我的代码:
<?php
require_once("dbconnect.php");
require_once("lib_isarabic.php");
$query = "SELECT COUNT( * ) cnt, hashtags
FROM tweets
WHERE tweeted_at >= DATE_SUB( NOW( ) , INTERVAL 2 DAY )
AND hashtags != ''
GROUP BY hashtags
ORDER BY cnt DESC LIMIT 100";
$res = mysql_query($query);
while($row = mysql_fetch_assoc($res) ) {
$count = $row['cnt'];
$hashtags = explode( " ", $row['hashtags'] );
foreach($hashtags as $hashtag ) {
if( strtolower($hashtag) != 'sudan' && strtolower($hashtag) != 'new' && strtolower($hashtag) != 'new' )
if( is_arabic($hashtag) )
$topics_ara[strtolower( trim($hashtag) )] += $count;
else
$topics_eng[strtolower( trim($hashtag) )] += $count;
}
}
array_multisort($topics_ara, SORT_DESC);
array_multisort($topics_eng, SORT_DESC);
$index = 0;
foreach($topics_eng as $key=>$value) {
$query = "SELECT count(*) cnt FROM (
SELECT count(*), tweeted_by FROM tweets
WHERE hashtags like '%$key%'
AND tweeted_at >= DATE_SUB( NOW( ) , INTERVAL 2 DAY )
GROUP BY tweeted_by
) AS T";
/* $query = "
SELECT count(*) FROM tweets
WHERE hashtags like '%$key%'
AND tweeted_at > DATE_SUB( NOW( ) , INTERVAL 1 DAY ) ";
*/
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
if($row['cnt'] > 1) {
$index++;
if($key != "" ) {
$trending_eng[$key] = $value;
}
}
if($index > 30)
break;
}
$index = 0;
foreach($topics_ara as $key=>$value) {
$query = "SELECT count(*) cnt FROM (
SELECT count(*), tweeted_by FROM tweets
WHERE hashtags like '%$key%'
AND tweeted_at >= DATE_SUB( NOW( ) , INTERVAL 2 DAY )
GROUP BY tweeted_by
) AS T";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
if($row['cnt'] > 1) {
$index++;
if($key != "" ) {
$trending_ara[$key] = $value;
}
}
if($index > 30)
break;
}
//var_dump($trending_eng) ;
//var_dump($trending_ara) ;
?>
【问题讨论】:
-
请不要将
mysql_*函数用于新代码。它们不再维护,社区已经开始deprecation process。看到red box?相反,您应该了解prepared statements 并使用PDO 或MySQLi。如果您不能决定,this article 将帮助您选择。如果你想学习,here is good PDO tutorial。 -
Profile your code 然后提出具体问题。
-
@Truth - 感谢您发布该 PDO 教程;我也将它包含在我的 cmets 给使用 `mysql_*` 的人。
-
@pythonscript: gist.github.com/2911132
-
@Truth - 太棒了!我会记下那个页面。