[英]Mysql query, PHP counting
I have the following structure of a MySQL first table: 我有一个MySQL第一个表的以下结构:
http://www.clubmadam.com/zadatak.jpg http://www.clubmadam.com/zadatak.jpg
Structure of a MySQL second table: MySQL第二个表的结构:
http://www.clubmadam.com/country.jpg http://www.clubmadam.com/country.jpg
I need an SQL query to count number of cities in each country and summarise population for all cities in country; 我需要一个SQL查询来计算每个国家/地区的城市数量,并总结国家/地区所有城市的人口数量;
This is what I have so far: 这是我到目前为止:
$upit = "SELECT";
$rezultat = mysql_query($upit);
{
}
Can a MySQL handle this, or do I need to also use PHP? MySQL可以处理这个,还是我还需要使用PHP? How would I do this?
我该怎么做?
This really is SQL 101 stuff, I suggest you do a lot of reading 这真的是SQL 101的东西,我建议你做很多阅读
SELECT CountryCode,
COUNT(Name) as Cities,
SUM(Population) as Population
FROM <tablename>
GROUP BY CountryCode
If I understand correctly, this query will give a count of cities based on country: 如果我理解正确,此查询将根据国家/地区计算城市数量:
SELECT COUNT(*) AS CityCount, CountryCode, SUM(Population) AS CountryPopulation
FROM myTableName
GROUP BY CountryCode
Per your comment, here is how you can do it across multiple tables: 根据您的评论,以下是如何跨多个表执行此操作:
SELECT City.COUNT(*) AS CityCount, Country.LocalName, City.SUM(Population) AS CountryPopulation
FROM City, Country
GROUP BY City.CountryCode
This is a simple MySQL aggregation job using the SUM()
and COUNT()
aggregate funcions : 这是一个使用
SUM()
和COUNT()
聚合函数的简单MySQL聚合作业:
$sql = 'SELECT
CountryCode,
COUNT(ID) as numCities,
SUM(Population) as totalPopulation
FROM Cities
GROUP BY CountryCode';
$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
}
Count number of cities in Country-code 计算国家/地区代码中的城市数量
$upit = "SELECT COUNT(DISTINCT CountryCode) FROM table_name
$num_rows = mysql_num_rows($upit);
echo "$num_rows Rows\n";
Summarize population for all cities in Country-code 总结国家代码中所有城市的人口
Refer @Mark Baker Answer 请参阅@Mark Baker答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.