我有以下简化的查询:
Select
(select sum(f1) from tableA a where a.id = t.id) sum1,
(select sum(f2) from tableB b where b.id = t.id) sum2,
t.*
from Table t;
我希望重新使用sum1和sum2而不重新计算它们:
Select
(select sum(f1) from tableA a where a.id = t.id) sum1,
(select sum(f2) from tableB b where b.id = t.id) sum2,
sum1 + sum2 `sum3`,
t.*
from Table t;
当然,我可以执行以下查询,但这将不必要地使运行时间加倍:
Select
(select sum(f1) from tableA a where a.id = t.id) sum1,
(select sum(f2) from tableB b where b.id = t.id) sum2,
(select sum(f1) from tableA a where a.id = t.id) +
(select sum(f2) from tableB b where b.id = t.id) `sum3`,
t.*
from Table t;
甚至将sum1和sum2结果插入到临时表中,但无法成像,我正在忽略使mysql对求和字段进行一些有效查询的方法。
有没有更好,更有效的方法来重用求和字段?
最佳答案
尝试运行此查询,
select Resutl.*,Result.sum1+Result.sum2 as sum3 from(
SELECT (SELECT SUM(f1) FROM tableA a WHERE a.id = t.id) sum1,
(SELECT SUM(f2) FROM tableB b WHERE b.id = t.id) sum2,
t.*
FROM Table t)Result
)
希望它会有所帮助。