gpt4 book ai didi

php - Yii 关系在查询中生成 GROUP BY 子句

转载 作者:行者123 更新时间:2023-11-29 02:24:38 25 4
gpt4 key购买 nike

我有 User、Play 和 UserPlay 模型。这是用户模型中定义的关系,用于计算用户玩游戏的总时间。

'playedhours'=>array(self::STAT, 'Play', 'UserPlay(user_id,play_id)', 
'select'=>'SUM(duration)'),

现在我正在尝试使用用户 ID 查找持续时间总和。

$playedHours = User::model()->findByPk($model->user_id)->playedhours)/3600;

此关系需要花费大量时间来执行大量数据。然后查看关系生成的查询。

SELECT SUM(duration) AS `s`, `UserPlay`.`user_id` AS `c0` FROM `Play` `t` INNER JOIN    
`UserPlay` ON (`t`.`id`=`UserPlay`.`play_id`) GROUP BY `UserPlay`.`user_id` HAVING
(`UserPlay`.`user_id`=9);

UserPlay.user_id 上的 GROUP BY 花费了很多时间。因为我在这里不需要 Group by 子句。

我的问题是,如何避免上述关系中的 GROUP BY 子句。

最佳答案

STAT 关系根据定义是聚合查询,参见 Statistical Query .您不能在此处删除 GROUP BY 并对聚合数据进行有意义的查询。 SUM()、AVG() 等都是聚合函数,参见 GROUP BY Functions , 获取 MYSQL 支持的所有聚合函数的列表。

您的问题是您正在执行 HAVING 子句的计算。这不是必需的,因为 HAVING 在聚合发生后检查条件,您可以使用它来放置条件,例如 SUM(duration) > 500

基本上发生的事情是您首先将所有用户单独分组,然后过滤您想要的用户 ID。如果您改为使用 WHERE 子句来过滤之前而不是之后,那么聚合将仅针对您想要的用户,然后将其分组,您的查询会快得多。

Although Active Record is good at modelling data in an OOP fashion, it actually degrades performance due to the fact that it needs to create one or several objects to represent each row of query result. For data intensive applications, using DAO or database APIs at lower level could be a better choice

因此,最好是更改与模型函数的关系,直接使用 CommandBuilder 或 DAO API 查询 Db。像这样的东西

Class User extends CActiveRecord {

....
public function getPlayedhours(){
if(!isset($this->id)) // to prevent query running on a newly created object without a row loaded to it
return 0;
$played = Yii::app()->db->createCommand()
->select('SUM(duration)')
->from('play')
->join("user_play up","up.play_id = play.id")
->where("up.user_id =".$this->id)
->group("up.user_id")
->queryScalar();
if($played == null)
return 0;
else
return $played/3600 ;
}
....
}

如果查询仍然很慢,请尝试优化索引,实现缓存机制,并使用 explain 命令找出实际花费更多时间的原因,更重要的是原因。如果一切都不够好,请升级您的硬件。

关于php - Yii 关系在查询中生成 GROUP BY 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24773935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com