如何加快查询速度?

时间:2012-03-09 09:12:05

标签: performance caching yii

我正在使用yii框架创建一个网站来处理诗歌,文字和东西......

问题是数据库有超过250,000条消息记录和超过500,000条关键字和关系记录:S

我想说的是,我想根据键标签进行最佳查询以获取特定消息的所有相关消息。

我到目前为止所做的是缓存查询,但是第一次打开它时仍然很慢,这是一个大问题!

这是我的代码:

    public function getRelatedMessages()
    {
        $id = $this->id;
        $dependency = "select `messages`.id,count(id) as tag_count from messages left join `messages_tags` on `messages`.`id` = `messages_tags`.mid 
            where `messages_tags`.`tagid` in (select `tags`.`id` from tags left join `messages_tags` on tags.id = `messages_tags`.tagid 
            where `messages_tags`.`mid` = {$id}) and id <> {$id} group by id order by tag_count desc";
        $dependency =  Messages::model()->cache(900)->findAllBySql($dependency);
        foreach ($dependency as $dependency) {
            $dependency1[] = $dependency['id'];
        }
        $dependency = implode(", ", $dependency1);
        $sql = "select * from messages where id in ({$dependency})  limit 4";
        $relateds =  Messages::model()->findAllBySql($sql);
        $db = array();
        foreach($relateds as $related) {
            $db[] = $related;
        }
        if(!$relateds || count($db)<4) {
            $limit = 4-count($db);
            $sql = "select `messages`.id, `messages`.url_key, `messages`.photo_url, `messages`.message from messages order by rand(), likes desc, comments desc, impressions desc, reported asc limit {$limit};";

            $relateds =  Messages::model()->cache(900)->findAllBySql($sql);
            foreach($relateds as $related) {
                $db[] = $related;
            }
        }

        return $db;
    } 

上面的代码在过滤它们并对其进行排序后,从相关消息中仅选择4条记录。问题在于“按顺序排列”,但我需要它:S

抱歉,如果那太长了..

谢谢你:)

1 个答案:

答案 0 :(得分:0)

您可以通过不使用findAllBySql()并实例化所有ActiveRecord类来改进第一个查询。你不需要它们,所以使用这样的普通sql查询(查询保持不变但代码已经改变):

       // ...
       $dependency = $this->dbConnection->createCommand("
           select `messages`.id, count(id) as tag_count
           from messages left join `messages_tags` on `messages`.`id` = `messages_tags`.mid 
           where
               `messages_tags`.`tagid` in 
                  (select `tags`.`id` from tags left join `messages_tags` on tags.id = `messages_tags`.tagid where `messages_tags`.`mid` = {$id})
               and id <> {$id}
           group by id order by tag_count desc")->queryColumn();

       $dependency = implode(", ", $dependency);
       $sql = "select * from messages where id in ({$dependency})  limit 4";
       $relateds =  Messages::model()->findAllBySql($sql);
       // ...