0
select *, 
  (a / 100) as a_calc, 
  (select sum(a_calc) from foo where c = ? and d = ?) as a_calc_sum 
from foo 
where c = ? and d = ? 
order by a;

这里的目的是我想返回与原始查询匹配的所有行(没有总和),并让 mysql 为我计算 a_calc 的总和,而不是发出单独的查询。如果没有子选择,我似乎只能得到查询中的第一行,并附有正确的总和。

任何想法如何减少上述查询?

4

1 回答 1

0

我认为您希望避免为每一行运行子查询-方法如下:

select *, 
  a / 100 as a_calc,
  a_calc_sum
from foo 
join (select sum(a / 100) a_calc_sum from foo where c = ? and d = ?) x
where c = ? and d = ? 
order by a;
于 2013-07-31T14:13:57.847 回答