我有这个问题:
select
sum(if(idcasa = 254, gcasa, 0)) as casa,
sum(if(idvisitante = 254, gvisitante, 0)) as visitante
from partido
where idcasa = 254 or idvisitante = 254 and idpais = 1 and idtemporada = 1 and idcategoria = 1;
我想要的是添加结果,像这样:
sum(casa + visitante) as goles
最佳答案
我怀疑这是你想要的查询:
select sum(case when idcasa = 254 then gcasa else 0 end) as casa,
sum(case when idvisitante = 254 then gvisitante else 0 end) as visitante,
sum(case when idcasa = 254 then gcasa else gvisitante end) as total
from partido
where (idcasa = 254 or idvisitante = 254) and
idpais = 1 and
idtemporada = 1 and
idcategoria = 1;
首先,请注意 where
子句的变化——圆括号。我猜这是您真正想要的逻辑。
其次,只需将值添加到表达式中就足够简单了。您可以先使用子查询来定义值,然后再添加它们,但表达式足够简单。而且,子查询通常会在 MySQL 中产生性能开销。
第三,我将 if
替换为 case
。后者是条件表达式的 ANSI 标准。
关于mysql - 添加查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48441592/