有什么方法可以避免在SELECT查询中重复列表达式?我想除以一列的总和和计数,但想使用分配的名称,而不是重复SUM(value)/COUNT(value)
或使用子查询。这可能吗?如果是这样,是否通过不重复求和与计数的计算来加快查询速度,还是mysql记住已经计算出的表达式?
SELECT datalist.type, SUM(value) AS type_sum, COUNT(value) AS type_count, type_sum/type_count
FROM (...) AS datalist
GROUP BY datalist.type
抛出:#1054-字段列表中的未知列'type_sum'
答案 0 :(得分:1)
除非您将其放在外部查询中,否则这是唯一的方法。
SELECT datalist.type, SUM(value) AS type_sum, COUNT(value) AS type_count, SUM(value)/COUNT(value)
FROM (...) AS datalist
GROUP BY datalist.type
答案 1 :(得分:1)
一种解决方法是使用别名表进行预定义的计算,然后再从外部表中调用它,例如:
select d.type_sum/d.type_count as dividedValue from (SELECT datalist.type, SUM(value)
AS type_sum, COUNT(value) AS type_count
FROM (...) )AS d
GROUP BY d.type