Yii如何优化sum()查询

时间:2013-08-19 13:52:41

标签: yii

我想跳过foreach循环;

如何使用yii查询获取sum

$sql = 'select size_kb from comp_arch_stats where company_id = ' . ($model->company_id) . ' and arch_month = ' . $month . ' and arch_year = ' . $year . ';';
        $val = Yii::app()->db->createCommand($sql)->queryAll();
        $sum = 0;
        foreach ($val AS $result) {
            $sum += $result['size_kb'];
        }

2 个答案:

答案 0 :(得分:1)

“'从comp_arch_stats中选择sum(size_kb)作为size_kb,其中company_id ='。($ model-> company_id)”

答案 1 :(得分:0)

试试这个

$criteria=new CDbCriteria;
$criteria->select = 'sum(size_kb) AS KbCount';
$criteria->condition ="company_id = :company_id AND arch_month =:arch_month AND arch_year=:arch_year "
$criteria->params = array ( 
':company_id '=> $model->company_id,
':arch_month' => $month,
':arch_year' => $year,
);
comp_arch_stats::model()->findAll($criteria);