Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Alias Question

i am wondering why this fails

mysql> SELECT Continent C, Name, SurfaceArea
    -> FROM Country
    -> WHERE SurfaceArea = (
    -> SELECT MAX(SurfaceArea)
    -> FROM Country
    -> WHERE Continent = C);
ERROR 1054 (42S22): Unknown column 'C' in 'where clause'

its a answer provided by the certification guide for some sample exercises.

btw, for alias when do i have to use AS? isit optional?

like image 493
iceangel89 Avatar asked Jul 03 '26 09:07

iceangel89


1 Answers

In order to execute a correlated subquery, you need an alias for the outer table. You created an alias for the outer table's field. Take a look at the corrected code below, that has an alias for the table (Cou) that is referenced in the subquery (note that the field alias is not required so I removed it. There's no harm in adding it back if you wish):

SELECT Continent, Name, SurfaceArea
FROM Country Cou
WHERE SurfaceArea = 
(
    SELECT MAX(SurfaceArea)
    FROM Country
    WHERE Continent = Cou.Continent
);

Regarding the usage of AS, it's optional. For example, in the query above you could write Country AS Cou, it would be the same.

like image 99
Roee Adler Avatar answered Jul 04 '26 23:07

Roee Adler