2017-09-09 44 views
0

我在第7行創建了一個名爲total_city_pop的列別名。如何在SELECT子句中命名後立即使用列別名?

然後,在第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; 

謝謝。

+1

你不能。您需要使用子查詢或重複表達式。 –

+0

您可能會喜歡閱讀https://dev.mysql.com/doc/refman/5.7/en/problems-with-alias.html –

回答

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支持計算列的最新版本。這些將允許您將計算放在表格的定義中。

+0

太棒了,謝謝。 – Sebastian

相關問題