0

我有以下 MySQL 第一个表的结构:

http://www.clubmadam.com/zadatak.jpg

MySQL第二张表的结构:

http://www.clubmadam.com/country.jpg

我需要一个 SQL 查询来计算每个国家/地区的城市数量并汇总该国家/地区所有城市的人口;

这是我到目前为止所拥有的:

$upit = "SELECT";
$rezultat = mysql_query($upit);
{
}

MySQL 可以处理这个,还是我还需要使用 PHP?我该怎么做?

4

5 回答 5

1

这真的是 SQL 101 的东西,我建议你做很多阅读

SELECT CountryCode,
       COUNT(Name) as Cities,
       SUM(Population) as Population
  FROM <tablename>
 GROUP BY CountryCode
于 2013-04-10T16:21:37.497 回答
1

如果我理解正确,此查询将根据国家/地区提供城市计数:

SELECT COUNT(*) AS CityCount, CountryCode, SUM(Population) AS CountryPopulation
FROM myTableName
GROUP BY CountryCode

根据您的评论,您可以通过以下方式跨多个表执行此操作:

SELECT City.COUNT(*) AS CityCount, Country.LocalName, City.SUM(Population) AS CountryPopulation
FROM City, Country
GROUP BY City.CountryCode
于 2013-04-10T16:23:27.487 回答
0

统计 Country-code 中的城市数量

$upit = "SELECT COUNT(DISTINCT CountryCode) FROM table_name
$num_rows = mysql_num_rows($upit);
echo "$num_rows Rows\n";

汇总国家代码中所有城市的人口

参考@Mark Ba​​ker 答案

于 2013-04-10T16:26:47.623 回答
0

SUM()这是一个使用和COUNT() 聚合函数的简单 MySQL 聚合作业:

$sql = 'SELECT 
  CountryCode, 
  COUNT(ID) as numCities, 
  SUM(Population) as totalPopulation 
  FROM Cities 
  GROUP BY CountryCode';
于 2013-04-10T16:22:37.450 回答
0
$upit = "SELECT COUNT(ID) AS cities, SUM(Population) AS population, ContryCode FROM table GROUP BY CountryCode";
$result = mysql_query($upit);
while ($data = mysql_fetch_object($result)) {
    // $data->cities is the number of cities and $data->population the sum of people and $data->CountryCode the country code
}
于 2013-04-10T16:23:40.800 回答