当结果集为空时,我可以返回0
SELECT
SUM(`Uren`),
SUM(`Minuten`)
FROM
`Uren`
RIGHT JOIN `Project`
ON `Project`.`idProject` = `Uren`.`idProject`
RIGHT JOIN `Uursoort`
ON `Uursoort`.`idUursoort` = `Uren`.`idUursoort`
WHERE `idKlant` = 5
AND `Uren`.`Datum` > '2014-04-02'
GROUP BY `Uren`.`idProject`
首选输出(而不是空结果集):
sum('Uren') sum('Minuten')
0 0
当我这样做时:
SELECT
SUM(`Uren`),
SUM(`Minuten`)
FROM
`Uren`
RIGHT JOIN `Project`
ON `Project`.`idProject` = `Uren`.`idProject`
RIGHT JOIN `Uursoort`
ON `Uursoort`.`idUursoort` = `Uren`.`idUursoort`
WHERE `idKlant` = 5
AND `Uren`.`Datum` > '2014-04-02'
GROUP BY `Uren`.`idProject
我得到正确的输出,因为有数据。但我需要得到0作为回报。 我也在模型中试过这个:
function rapport_detail_uren($idKlant,$start,$eind){
$this->db->select_sum('Uren');
$this->db->select_sum('Minuten');
$this->db->from('Uren');
$this->db->join('Uursoort','Uursoort.idUursoort=Uren.idUursoort','right');
$this->db->join('Project','Project.idProject=Uren.idProject','right');
if ($idKlant > 0){
$this->db->where('idKlant',$idKlant);}
if ($start != NULL){
$this->db->where('Uren.Datum >=', $start);
}
$this->db->group_by('Uren.idProject');
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result();
}
else{
return 0;
}
}
最后一行返回0.我想也许这会将值返回为0但不起作用
答案 0 :(得分:1)
您可以将where
条件移动到除最后一个表之外的所有表的on
子句中(因为您使用right outer join
:
SELECT coalesce(SUM(`Uren`), 0), coalesce(SUM(`Minuten`), 0)
FROM `Uren` RIGHT JOIN
`Project`
ON `Project`.`idProject` = `Uren`.`idProject` AND
`Uren`.`Datum` > '2014-04-02' RIGHT JOIN
`Uursoort`
ON `Uursoort`.`idUursoort` = `Uren`.`idUursoort`
WHERE `idKlant` = 5 AND
GROUP BY `Uren`.`idProject`;
就个人而言,我发现left outer join
更容易理解("保留第一个表中的所有行"对#"保留最后一个表中的所有行"),但相同的原则适用:where
条件可以将外连接转换为内连接,因为外连接会生成意外的NULL
值。
您可能还必须将idklant
移至on
子句。我质疑为什么要按uren.idProject
进行汇总,可能会有NULL
个值。
答案 1 :(得分:0)
使用SUMs执行此操作:
SELECT IFNULL(SUM(Uren),0),IFNULL(SUM(Minuten),0)
我还必须这样做,但是DB2和DB2没有标准化,以解决同样的问题。
SELECT 0,0
UNION ALL
SELECT SUM(Uren), SUM(Minuten)
答案 2 :(得分:0)
这应该有效:
SELECT
SUM( `Uren` ) AS SUM_Uren,
SUM( `Minuten` ) AS SUM_Minuten
FROM
(
SELECT
`Uren`.`idProject
IF( count( `Uren` ) > 0, `Uren`, 0 ) AS `Uren`,
IF( count( `Minuten` ) > 0, `Minuten`, 0 ) AS `Minuten`
FROM `Uren`
RIGHT JOIN `Project`
ON `Project`.`idProject` = `Uren`.`idProject`
RIGHT JOIN `Uursoort`
ON `Uursoort`.`idUursoort` = `Uren`.`idUursoort`
WHERE `idKlant` = 5
AND `Uren`.`Datum` > '2014-04-02'
) results
GROUP BY `idProject`
答案 3 :(得分:0)
你问的不容易。 (或者至少它变得笨拙。)你的select语句返回零,一行或多行。如果它返回none,则需要生成一行。所以你必须执行两次声明;一次用于正常行,一次用于确定是否需要创建一个附加行:
select col1, col2 -- <= your statement
from some tables
where some criteria
UNION ALL -- Add ...
select 0, 0 -- ... a record containing zeros, but ...
where not exists -- ... due to this clause only when your query returns no records.
(
select col1, col2 -- <= your statement again
from some tables
where some criteria
);
只需复制并粘贴您自己的声明(我仍然认为这是可疑的btw)。