可以在外部查询中使用子查询中的数据吗?

时间:2013-08-09 22:32:00

标签: mysql subquery

对于这个糟糕的问题标题感到抱歉,我不确定是否有我正在尝试做的名字。

我想查询如下:

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'

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;

答案 2 :(得分:1)

由于def是标量值,您可以引入用户定义的变量来保存值并使用它们来执行计算:

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