在MySQL中使用字段操作的最有效方法是什么?

时间:2016-04-27 12:04:26

标签: mysql math operations

我有以下查询:

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

是否有更有效的“数据”操作方式?有没有办法在不使用 UNION 的情况下执行此操作?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用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

答案 1 :(得分:0)

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

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

CV_64F