这一定是一件非常容易的事情,但我无法完成任务,也无法在任何地方找到。这就是我的select
代码:
SELECT *,
(SELECT SUM(x) FROM a WHERE (...)) AS sum_x,
(SELECT SUM(y) FROM b WHERE (...)) AS sum_y
FROM table
我想使用(sum_x - sum_y)
再创建一个字段,但是当我尝试做这样的事情时
SELECT *,
(SELECT SUM(x) FROM a WHERE (...)) AS sum_x,
(SELECT SUM(y) FROM b WHERE (...)) AS sum_y,
(sum_x - sum_y) AS sum_c
FROM table
它对我生气并说Unknown column 'sum_x' in 'field list'
。
我在这里缺少什么?
答案 0 :(得分:5)
SQL通常不允许您在定义它们的同一级别引用列别名。您需要使用子查询执行此操作:
select t.*, (sum_x - sum_y) as sum_c
from (SELECT *,
(SELECT SUM(x) FROM a WHERE (...)) AS sum_x,
(SELECT SUM(y) FROM b WHERE (...)) AS sum_y
FROM table
) t;
然而,MySQL倾向于实现子查询,因此存在性能损失。实现的开销可能少于两次子查询计算:
SELECT *,
(SELECT SUM(x) FROM a WHERE (...)) AS sum_x,
(SELECT SUM(y) FROM b WHERE (...)) AS sum_y,
((SELECT SUM(x) FROM a WHERE (...)) -
(SELECT SUM(y) FROM b WHERE (...))
) as sum_c
FROM table;
只进行一次计算也更容易维护和理解。
在MySQL中,你也可以这样做:
SELECT *,
@sum_x := (SELECT SUM(x) FROM a WHERE (...)) AS sum_x,
@sum_y := (SELECT SUM(y) FROM b WHERE (...)) AS sum_y,
(@sum_x - @sum_y) as sum_c
FROM table cross join
(select @sum_x := 0, @sum_y := 0) const
MySQL不保证在分配后评估最后一个表达式。它似乎在实践中始终如此。
答案 1 :(得分:2)
试试这个
SELECT *,
(SELECT SUM(x) FROM a WHERE (...)) AS sum_x,
(SELECT SUM(y) FROM b WHERE (...)) AS sum_y,
(SELECT SUM(x) FROM a WHERE (...) - (SELECT SUM(y) FROM b WHERE (...))) AS sum_c
FROM table
答案 2 :(得分:1)
只需使用子查询而不是使用别名
SELECT *,
(SELECT SUM(x) FROM a WHERE (...)) AS sum_x,
(SELECT SUM(y) FROM b WHERE (...)) AS sum_y,
(
(SELECT SUM(x) FROM a WHERE (....)) - (SELECT SUM(y) FROM b WHERE (...))
) AS sum_c
FROM table