如何在SQL中重用子查询的结果

时间:2018-10-03 07:28:13

标签: sql postgresql

我是SQL的新手,我正在使用postgres运行我的sql。我在重用子查询时遇到问题。

这是我当前拥有的子查询。

    SELECT country.name, city.name, country.continent
    FROM country
    INNER JOIN city
    ON country.code = city.countrycode
    ORDER BY city.population DESC
    LIMIT 10;

我正在输出2个不同的表,并且我根据其代码内部加入城市和国家。我按最高人口到最低人口的顺序排列它们,并只选择前十名。 该子查询的结果显示为:

            name        |       name       |   continent   
    --------------------+------------------+---------------
     India              | Mumbai (Bombay)  | Asia
     South Korea        | Seoul            | Asia
     Brazil             | São Paulo        | South America
     China              | Shanghai         | Asia
     Indonesia          | Jakarta          | Asia
     Pakistan           | Karachi          | Asia
     Turkey             | Istanbul         | Asia
     Mexico             | Ciudad de México | North America
     Russian Federation | Moscow           | Europe
     United States      | New York         | North America

现在的问题是,我该如何重用这些结果并找出哪个城市也是该国的首都。

所以我在重用上面的结果后的预期输出是:

         name      |   name    |   continent   
    ---------------+-----------+---------------
     South Korea   | Seoul     | Asia
     Brazil        | São Paulo | South America
     China         | Shanghai  | Asia
     Turkey        | Istanbul  | Asia
     United States | New York  | North America

为了实现预期的输出,我认为我需要使用以下行:

    WHERE city.name = city.district

我已经检查了诸如WITH之类的子句,但不确定如何使用它。

2 个答案:

答案 0 :(得分:3)

您可以尝试以下方式

with t1 as
(
SELECT country.name as country_name, city.name as cityname, country.continent
    FROM country
    INNER JOIN city
    ON country.code = city.countrycode
    ORDER BY city.population DESC
    LIMIT 10;
) select t1.* from t1 join city c on t1.cityname=c.district

答案 1 :(得分:0)

我会这样:

SELECT country_name, city_name, continent
FROM (SELECT co.name as country_name, ci.name as city_name, co.continent, ci.district
      FROM country co INNER JOIN
           city ci
           ON co.code = ci.countrycode
      ORDER BY ci.population DESC
      LIMIT 10
     ) cc
WHERE district = city_name;

换句话说,您不需要额外的JOIN。您只需在子查询/ CTE中选择所需的列即可。