Mysql查询,PHP计数

时间:2013-04-10 16:18:47

标签: php mysql

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

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

MySQL第二个表的结构:

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

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

这是我到目前为止所做的:

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

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

5 个答案:

答案 0 :(得分:1)

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

SELECT CountryCode,
       COUNT(Name) as Cities,
       SUM(Population) as Population
  FROM <tablename>
 GROUP BY CountryCode

答案 1 :(得分: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

答案 2 :(得分:0)

这是一个简单的MySQL聚合工作,使用SUM()COUNT() aggregate funcions

$sql = 'SELECT 
  CountryCode, 
  COUNT(ID) as numCities, 
  SUM(Population) as totalPopulation 
  FROM Cities 
  GROUP BY CountryCode';

答案 3 :(得分: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
}

答案 4 :(得分:0)

计算国家/地区代码

中的城市数量
$upit = "SELECT COUNT(DISTINCT CountryCode) FROM table_name
$num_rows = mysql_num_rows($upit);
echo "$num_rows Rows\n";

汇总国家/地区代码

中所有城市的人口

请参阅@Mark Ba​​ker答案