编写从PHP中的多个表中获取信息的查询

时间:2014-10-13 03:19:49

标签: php sql postgresql

当我尝试运行查询时出现错误,我无法弄清楚原因。这是我作业的最后一步,我一直在努力解决这个问题。我想写的查询是。

List the country name, it’s population, and the sum of the populations of all cities in   
that country. Add a fourth field to your query that calculates the percent of urban 
population for each country. (For the purposes of this example, assume that the sum of the 
populations of all cities listed for a country represent that country’s entire urban 
population.) Order the results of this query in increasing order of urban population 
percentage.

我现在收到的错误是

Warning: pg_query(): Query failed: ERROR: column "cnt.population" must appear in the 
GROUP BY clause or be used in an aggregate function LINE 2

我的代码是

$query ="SELECT cnt.name AS country_name, 
cnt.population AS total_population, 
SUM(cty.population)/(cnt.population) * 100 AS urban_percentage
FROM     what.country cnt 
JOIN     what.city cty ON cty.country_code = cnt.country_code 
GROUP BY cnt.name 
ORDER BY 3 ASC";

我正在使用的两个表是

Table "what.country"
     Column      |         Type          |               Modifiers              
-----------------+-----------------------+--------------------------------------
 country_code    | character(3)          | not null default ''::bpchar
 name            | character varying(52) | not null default ''::character varying
 continent       | continent             | not null
 region          | character varying(26) | not null default ''::character varying
 surface_area    | real                  | not null default 0::real
 indep_year      | smallint              | 
 population      | integer               | not null default 0
 life_expectancy | real                  | 
 gnp             | real                  | 
 gnp_old         | real                  | 
 local_name      | character varying(45) | not null default ''::character varying
 government_form | character varying(45) | not null default ''::character varying


    Table "what.city"
    Column    |         Type          |                     Modifiers                    
--------------+-----------------------+-----------------------------------------
 id           | integer               | not null default nextval('city_id_seq'::regclass)
 name         | character varying(35) | not null default ''::character varying
 country_code | character(3)          | not null default ''::bpchar
 district     | character varying(20) | not null default ''::character varying
  population   | integer               | not null default 0

1 个答案:

答案 0 :(得分:0)

您可以将MAX用于城市人口,因为您在城市名称上进行GROUP BY,该城市的人口只有一个值

  $query ="SELECT cnt.name AS    country_name, 
   Max(cnt.population) AS   total_population, 
   SUM(cty.population),  SUM(cty.population)/max(cnt.population) * 100 AS urban_percentage
    FROM     what.country cnt 
    JOIN     what.city cty ON   cty.country_code = cnt.country_code 
    GROUP BY cnt.name";