2013-05-09 62 views
1

我有一個包含3個字段(id,jobsprocess,percent)的表,並且想要計算出即時累計百分比,所以它是派生字段。如何在yii中運行累積派生查詢

在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

我也曾嘗試th3e以下,但我得到一個錯誤

$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

可以聲明在你的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();