如何在SELECT子句中命名后立即使用列别名?

时间:2017-09-09 17:39:03

标签: mysql sql column-alias

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

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

但是,我收到一条错误消息,上面写着"列" total_city_pop"不存在LINE 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;

谢谢。

1 个答案:

答案 0 :(得分:3)

You need to repeat the expression in the subquery. However, I would suggest you simplify the expression using 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;

The most recent versions of MySQL support computed columns. These would allow you to put the computation in the definition of the table.