计算字段的总和

lvi*_*vil 4 mysql sql aggregate-functions mysql-error-1054

我有两张桌子:

  • table1(a,b,c)
  • table2(a,d,f)

我想得到每个b得到相应的d和f的乘法和

表1数据

a   b      c
-------------
1   hello  3
2   bye    4
Run Code Online (Sandbox Code Playgroud)

表2数据

a  d  f
--------
1  5  3
1  2  4
2  1  3
2  2  3
Run Code Online (Sandbox Code Playgroud)

结果:你好:5*3 + 2*4,再见:1*3 + 2*3
我的查询是:

  SELECT t1.a, 
         t2.d * t2.f AS m, 
         SUM(m)   
    FROM table1 AS t1, 
         table2 AS t2 
   WHERE t1.a = t2.a 
GROUP BY t1.b
Run Code Online (Sandbox Code Playgroud)

那么这里有什么问题?在mysql中我得到#1054 - '字段列表'中的未知列'm'

dka*_*ins 5

尝试:

SELECT t1.a, t2.d*t2.f AS m, SUM(t2.d*t2.f)
FROM table1 AS t1, table2 AS t2 
WHERE t1.a=t2.a GROUP BY t1.b
Run Code Online (Sandbox Code Playgroud)

(即扩展别名)


OMG*_*ies 5

您不能在同一SELECT子句中引用列别名-您要么需要重现公式:

  SELECT t1.a, 
         t2.d * t2.f AS m, 
         SUM(t2.d * t2.f)   
    FROM table1 AS t1 
    JOIN table2 AS t2 ON t1.a = t2.a 
GROUP BY t1.b
Run Code Online (Sandbox Code Playgroud)

..或使用派生表/内联视图:

SELECT x.a,
       x.m, 
       SUM(x.m)
  FROM (SELECT t1.a, 
               t2.d * t2.f AS m
          FROM table1 AS t1 
          JOIN table2 AS t2 ON t1.a = t2.a 
      GROUP BY t1.b) x
Run Code Online (Sandbox Code Playgroud)

最早的MySQL允许引用列别名的是GROUP BY子句(HAVING并且ORDER BY还支持列别名)。但是大多数其他数据库仅支持该ORDER BY子句。