2013-12-18 77 views
3

我有以下查詢不返回行。但是,如果發生這種情況,我想將值設置爲0或null。我該怎麼做呢?mysql設置爲空或0,如果右連接返回無行

UPDATE `hdb`.`projects` 
RIGHT JOIN (
    SELECT jobs.PROJID, round(SUM(jobs.value),2) AS SumOfJobValues, round(Sum(jobs.Earned),2) AS SumOfEarnedValues 
    FROM jobs 
    WHERE projects.PROJID = 1312184 
    GROUP BY jobs.PROJID 
) as temp ON projects.PROJID = temp.PROJID 
SET 
    projects.VALUE = round(SumOfJobValues,2), 
    projects.WIP = round(SumOfEarnedValues,2) 

我重寫了我的查詢使用左連接,它在MySQL中工作。然而,當我運行這個使用php Yii框架我不工作。

UPDATE `hdb`.`projects` 
left JOIN (
    SELECT 
    jobs.PROJID, 
    round(SUM(jobs.value),2) AS SumOfJobValues, 
    round(Sum(jobs.Earned),2) AS SumOfEarnedValues 
    FROM jobs   
    GROUP BY jobs.PROJID 
) as temp ON projects.PROJID = temp.PROJID 
SET 
    projects.VALUE = round(SumOfJobValues,2), 
    projects.WIP = round(SumOfEarnedValues,2) 
WHERE projects.PROJID = 1312184 

上運行PHP的Yii

$sql = "UPDATE `hdb`.`projects` 
    LEFT JOIN (
    SELECT 
     jobs.PROJID, round(SUM(jobs.value),2) AS SumOfJobValues, 
     round(Sum(jobs.Earned),2) AS SumOfEarnedValues 
    FROM jobs 
    WHERE jobs.PROJID = :pid          
    GROUP BY jobs.PROJID 
    as temp ON projects.PROJID = temp.PROJID        
    SET 
     projects.VALUE = round(SumOfJobValues,2), 
     projects.WIP = round(SumOfEarnedValues,2) 
    WHERE projects.PROJID = :pid"; 

$command=$connection->createCommand($sql); 
$command->bindValue(":pid",$model->PROJID,PDO::PARAM_INT); 
$command->execute(); 
+0

爲什麼不只是價值和wip有一個默認值0? –

+0

'project.VALUE'和'projects.WIP'已經有了值。 '項目'可以有許多'工作'記錄。一旦我刪除了所有的工作記錄,我想更新'項目'中的值,如果可能的話,寧願在1個查詢中執行。 – shorif2000

+0

謝里夫,你爲什麼刪除你自己的答案?這似乎是正確的解決方案。 – RandomSeed

回答

0

相同的查詢你忘了對你的Yii查詢10號線之前關閉括號。另外,如果你不想加入NULL值,你可以使用 「IS NOT NULL」 在你的JOIN定義是這樣的:

UPDATE `hdb`.`projects` 
left JOIN (
    SELECT 
    jobs.PROJID, 
    round(SUM(jobs.value),2) AS SumOfJobValues, 
    round(Sum(jobs.Earned),2) AS SumOfEarnedValues 
    FROM jobs   
    GROUP BY jobs.PROJID 
) as temp ON (projects.PROJID = temp.PROJID) AND (temp.PROJID IS NOT NULL) 
SET 
    projects.VALUE = round(SumOfJobValues,2), 
    projects.WIP = round(SumOfEarnedValues,2) 
WHERE projects.PROJID = 1312184 

編輯:我沒有測試過這一點,雖然。