如果右连接没有返回任何行,则mysql设置为null或0

时间:2013-12-18 16:57:01

标签: php mysql yii sql-update right-join

我有以下查询,它不返回任何行。但是,如果发生这种情况,我想将值设置为0或null。我该怎么做?

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();

1 个答案:

答案 0 :(得分:0)

您忘记在Yii查询的第10行之前关闭括号。此外,如果您不想加入NULL值,可以在JOIN定义中使用“IS NOT NULL”,如:

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

编辑:我没有测试过这个。