我有两张桌子:
我想让每个b得到相应d和f
的乘法和a b c
-------------
1 hello 3
2 bye 4
a d f
--------
1 5 3
1 2 4
2 1 3
2 2 3
结果:你好: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
那么这里有什么问题?在mysql中,我得到#1054 - '字段列表'中的未知列'm'
答案 0 :(得分: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
(即扩展别名)
答案 1 :(得分:4)
您不能在同一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
..或使用派生表/内联视图:
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
最早的MySQL允许引用列别名是GROUP BY
子句(HAVING
和ORDER BY
也支持列别名)。但是大多数其他数据库只支持ORDER BY
子句。