简体   繁体   中英

Replacing Inner Join with a SubQuery in SQL

Pardon if this question is too simple as I am in the process of learning how to write a subquery. I came across this guide online, which shows an example of how a SQL statement with INNER JOIN can be replaced by one with a Subquery in the SELECT clause.

There are 2 tables - Countries (code, name, continent, region, surface_area) and Cities (name, country_code, city_proper_pop, metroarea_pop).

SQL statement with INNER JOIN

SELECT countries.name AS country, COUNT(*) AS cities_num
      FROM cities
        INNER JOIN countries
        ON countries.code = cities.country_code
    GROUP BY country
    ORDER BY cities_num DESC, country
    LIMIT 9;

This returns the table: 在此处输入图片说明

Next, this statement is replaced by a SQL statement with a Subquery in the SELECT clause

    SELECT countries.name AS country,
      (SELECT COUNT(*)
       FROM cities
       WHERE countries.code = cities.country_code) AS cities_num
    FROM countries
    ORDER BY cities_num DESC, country
    LIMIT 9;

which shows the same resulting table .

My question is: I am unsure why the nested SQL query can contain this condition countries.code = cities.country_code in the WHERE clause without performing any Join. Because the nested query only draws result from cities table , it does not specify the countries table .

Hope someone can explain to me. Thank you in advance.

This is called correlated sub query.

For every row of outer query, it will run the inner query, in programming terms something like loop inside a loop.

More info..

https://www.geeksforgeeks.org/sql-correlated-subqueries/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM