0

我在第 7 行创建了一个名为 total_city_pop 的列别名。

然后,在第 8 行,我尝试在新计算中使用该别名。

但是,我收到一条错误消息,上面写着“列“total_city_pop”不存在第 8 行:(ci.city_proper_pop + ci.metroarea_pop)/total_city_pop AS ... ^”

为什么我创建后不能使用别名?

这是代码——

SELECT co.code, ci.name AS capital_city, ci.city_proper_pop, ci.metroarea_pop, ci.urbanarea_pop,
    CASE
        WHEN (ci.city_proper_pop + ci.metroarea_pop + ci.urbanarea_pop) IS NULL
        THEN (ci.city_proper_pop + ci.urbanarea_pop)
        ELSE (ci.city_proper_pop + ci.metroarea_pop + ci.urbanarea_pop) END AS total_city_pop, 
    (ci.city_proper_pop + ci.metroarea_pop) / total_city_pop AS percent_outside_urbanarea 
FROM countries AS co 
    INNER JOIN cities AS ci ON co.capital = ci.name 
    WHERE continent LIKE '%America%' OR continent LIKE 'Europe'     
    ORDER BY total_city_pop DESC 
    LIMIT 10;

谢谢你。

4

1 回答 1

3

您需要在子查询中重复该表达式。但是,我建议您使用以下方法简化表达式COALESCE()

SELECT co.code, ci.name AS capital_city, ci.city_proper_pop, ci.metroarea_pop, ci.urbanarea_pop,
       (ci.city_proper_pop + ci.metroarea_pop + COALECE(ci.urbanarea_pop, 0) ) as  total_city_pop, 
       (ci.city_proper_pop + ci.metroarea_pop) / (ci.city_proper_pop + ci.metroarea_pop + COALECE(ci.urbanarea_pop, 0) ) AS percent_outside_urbanarea 
FROM countries co INNER JOIN
     cities ci
     ON co.capital = ci.name 
WHERE continent LIKE '%America%' OR continent LIKE 'Europe'     
ORDER BY total_city_pop DESC 
LIMIT 10;

MySQL 的最新版本支持计算列。这些将允许您将计算放在表的定义中。

于 2017-09-09T17:44:13.793 回答