SELECT Y/X as Z
FROM (
SELECT
(count(county) FROM `cleanup_site_list_2011` WHERE county='kings') as X,
(count(county) FROM `cleanup_site_list_2011` WHERE county='kings' AND people != 0) as Y
FROM `cleanup_site_list_2011`
) as innertable
在上面的例子中,两个“SELECT ...”表示任何描述的嵌套查询(X和Y将是整数)。当我尝试使用此语句时,我收到错误
#1054 - Unknown column 'Y' in 'field list'
如何让MySQL识别我创建的列的名称?此外,一旦数学计算出来,我如何在浮点数中得到除法结果?或者它会自动执行此操作吗?
答案 0 :(得分:1)
解决这个问题的一种方法是在子查询中为列提供“自定义名称”,然后在周围的查询中使用这些自定义名称:
SELECT
Y/X as Z -- moved to outer query
FROM (
SELECT
(...) as X, -- assign custom names in subquery
(...) as Y,
FROM `table`
) as innertable;
关于第二个问题:
mysql> select 4 / 3;
+--------+
| 4 / 3 |
+--------+
| 1.3333 |
+--------+
1 row in set (0.00 sec)
这回答了吗? (MySQL 5)
更多信息here。
答案 1 :(得分:0)
SELECT t1.x, t2.y, t2.y/t1.x z
FROM (SELECT x ...) t1,
(SELECT y ...) t2,
FROM `table`