对 MySQL 中的字段进行操作的最有效方式是什么?

What's the most efficient way of operating with fields in MySQL?

我有以下查询:

SELECT DATE(utimestamp) as utimestamp, name, data*2000000 from tData 
where utimestamp BETWEEN '2016-01-01 00:00:00' AND '2016-04-16 00:00:00' 
AND name = 'Valor2' and data>20
group by YEAR(utimestamp), MONTH(utimestamp), name 
union
SELECT DATE(utimestamp) as utimestamp, name, data*0.1 from tData 
where utimestamp BETWEEN '2016-01-01 00:00:00' AND '2016-04-16 00:00:00' 
AND name = 'Valor1' and data>20 
group by YEAR(utimestamp), MONTH(utimestamp), name 
order by utimestamp asc

'data'有没有更有效的操作方式?有没有办法不使用 UNION?

你可以尝试使用case when then:

SELECT DATE(utimestamp) as utimestamp, name, 
case when name = 'Valor1' then data*0.1
     when name = 'Valor2' then data*2000000 
end
from tData 
where utimestamp BETWEEN '2016-01-01 00:00:00' AND '2016-04-16 00:00:00' 
and data>20 
group by YEAR(utimestamp), MONTH(utimestamp), name 
order by utimestamp asc

你问题中的查询很奇怪,因为它有一个没有聚合函数的数学计算。而且,您按年和月聚合,但不将它们包括在查询中。

我倾向于将值放在两个单独的列中,并在查询中明确定义年份和月份:

select year(utimestamp), month(utimestamp),
       sum(case when name = 'Valor1' then data*0.01 end) as valor1,
       sum(case when name = 'Valor2' then data*2000000 end) as valor2
from tData 
where utimestamp between '2016-01-01' and '2016-04-16' and
      name in ('Valor1', 'Valor2') and 
      data > 20
group by year(utimestamp), month(utimestamp)
order by max(utimestamp);