我有这个问题:
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
答案 0 :(得分:2)
我怀疑这是你想要的查询:
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标准。
答案 1 :(得分:1)
WITH temp AS (
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
)
SELECT sum(casa + visitante) as goles FROM temp;