如何在查询中为每个国家/地区选择一行

时间:2013-10-04 20:03:45

标签: sql database postgresql

我明白了。 SELECT DISTINCT ON(country.name)country.name AS country ... working

我正在进行查询以获得每个国家/地区的单个最大城市(就人口而言)。问题是某个国家的某些城市与同一群体并列,因此查询返回的是每个国家/地区不止一个城市。 (我已经尝试过SELECT DISTINCT country.name,但它给了我相同的输出)

有什么想法吗?

这是我的代码:

        $query = "SELECT country.name AS country, largest_city, sq.pop AS population
        FROM lab6.country INNER JOIN 

        (SELECT MAX(city.population) AS pop, country_code 
        FROM lab6.city 
        GROUP BY country_code) AS sq
        USING (country_code)

        INNER JOIN

        (SELECT city.name AS largest_city, city.population
        FROM lab6.city) AS sq1
        ON (sq1.population = sq.pop)

        ORDER BY country.name ASC";

1 个答案:

答案 0 :(得分:1)

每个OP:

  

我明白了。 SELECT DISTINCT ON(country.name)country.name AS   国家......工作

现在我们可以看到这个问题在没有提出问题的情况下有了答案。