1

抱歉,问题标题很糟糕,我不确定我正在尝试做的事情是否有名称。

我想有如下查询:

SELECT a, b, c, (d + e - f) as computedValue,

(SELECT SUM(column1) FROM table2) as d,
(SELECT SUM(column2) FROM table3) as e,
(SELECT SUM(column3) FROM table4) as f,

FROM table1
WHERE a = 1

所以,换句话说,我想使用从子查询返回的整数值来计算一个值。我可以在 PHP 中这样做:

$computedValue = $row['d'] + $row['e'] - $row['f'];

但我想知道是否可以在查询本身中执行此操作?

当我尝试时,出现以下错误:

错误!:SQLSTATE [42S22]:找不到列:1054 '字段列表'中的未知列 'd'

4

3 回答 3

2

您不能在同一查询的大多数子句中使用列别名,包括在选择列表中。
对于许多 SQL 开发人员来说,这似乎令人费解,但这是标准 SQL。

但是您可以像这样使用派生表子查询:

SELECT *, (d + e - f) as computedValue 
FROM (
    SELECT a, b, c,    
    (SELECT SUM(column1) FROM table2) as d,
    (SELECT SUM(column2) FROM table3) as e,
    (SELECT SUM(column3) FROM table4) as f    
    FROM table1
    WHERE a = 1
) AS x;
于 2013-08-09T22:42:10.577 回答
1

As d, e and f are scalar values, you could introduce user-defined variables to hold the values and use them to perform your calculations:

SELECT a, b, c,

@d := (SELECT SUM(column1) FROM table2) as d,
@e := (SELECT SUM(column2) FROM table3) as e,
@f := (SELECT SUM(column3) FROM table4) as f,

(@d + @e - @f) as computedValue

FROM table1
WHERE a = 1
于 2013-08-09T23:01:23.237 回答
1

一个 Select 语句字段可以包含其他 select 语句作为字段。然后,您可以对这些选定的值进行数学运算,然后通过AS.

SELECT a, b, c, 
   (
       (SELECT SUM(column1) FROM table2) +
       (SELECT SUM(column2) FROM table3) -
       (SELECT SUM(column3) FROM table4)
   ) as computedValue
FROM table1
WHERE a = 1;
于 2013-08-09T22:45:09.063 回答