如何在yii中运行累积派生查询

时间:2013-05-09 14:38:22

标签: php mysql yii derived cumulative-sum

我有一个包含3个字段(id,jobsprocess,percent)的表,并希望动态计算累积百分比,因此它是派生字段。

在sql中我会这样做,返回13条记​​录。

set @x := 0;
SELECT ID, jobsprocess, PERCENT, (@x := @x + PERCENT) AS cumaltive
FROM `hdb`.`lookupprocess`
inner join jobsprocess on jobprocess = process_id
where projid = 1302035
order by id

我怎么能在yii中这样做?到目前为止,我有以下内容,但它没有给我我想要的结果

$lastrun = Yii::app()->db->createCommand("
                    SELECT ID, jobsprocess, PERCENT , (:criteria = :criteria + PERCENT) AS cumulative
                    FROM `hdb`.`lookupprocess`
                    inner join jobsprocess on jobprocess = process_id
                    where projid = $projid
                    order by id " )->queryAll(true, array(':criteria'=>0));

返回13条记​​录,但累计值始终为0。

我也尝试了以下但是我收到了错误

$user = Yii::app()->db->createCommand()
    ->select('ID, jobsprocess, PERCENT , (:zero := (:zero + PERCENT)) AS cumulative')
    ->from('lookupprocess')
    ->join('jobsprocess','jobprocess = process_id')
    ->where('projid = :projid', array(':projid'=>$projid,':zero'=>0))

    ->queryAll();

它需要:zero作为字符串。

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':= ('0' + PERCENT)) AS cumulative
FROM `lookupprocess`
JOIN `jobsprocess` ON job' at line 1. The SQL statement executed was: SELECT ID, jobsprocess, PERCENT , (:zero := (:zero + PERCENT)) AS cumulative
FROM `lookupprocess`
JOIN `jobsprocess` ON jobprocess = process_id
WHERE projid = :projid 

1 个答案:

答案 0 :(得分:1)

您可以在查询的FROM部分声明SQL变量:

SELECT ID, jobsprocess, PERCENT, (@x := @x + PERCENT) AS cumaltive
FROM `hdb`.`lookupprocess`, (SELECT @x=0) q
inner join jobsprocess on jobprocess = process_id
where projid = 1302035
order by id

所以,像这样:

$lastrun = Yii::app()->db->createCommand("
    SELECT ID, jobsprocess, PERCENT , (@x := @x + PERCENT) AS cumulative
    FROM `hdb`.`lookupprocess`, (SELECT @x:=0) q
    inner join jobsprocess on jobprocess = process_id
    where projid = $projid
    order by id " )->queryAll();