基本加入mysql

时间:2016-06-16 17:29:03

标签: mysql join

我现在一直在研究这个基本的内部联接,但我似乎无法让它工作。问题是:

  

根据CITY和COUNTRY表格,查询所有大陆的名称(COUNTRY.Continent)及其各自的平均城市人口(CITY.Population),向下舍入到最接近的整数。

以下SQL将查询一个大陆的普通城市人口,但我无法弄清楚如何概括它。

SELECT DISTINCT cc.NAME, AVG(c.POPULATION) FROM
CITY c
INNER JOIN COUNTRY cc 
ON c.COUNTRYCODE = cc.CODE
WHERE cc.CONTINENT = 'a continent'
ORDER BY cc.CONTINENT;

The City Table The Country Table

3 个答案:

答案 0 :(得分:1)

您希望获得具有国家/地区名称的普通人口。所以你在查询中使用group by。

使用以下查询:

SELECT cc.NAME, FLOOR(AVG(c.POPULATION)) AS population FROM
CITY c
INNER JOIN COUNTRY cc 
ON c.COUNTRYCODE = cc.CODE
WHERE cc.CONTINENT = 'a continent'
GROUP BY cc.NAME
ORDER BY cc.CONTINENT;

答案 1 :(得分:1)

圆形平均城市人口为FLOOR(AVG(c.population))

SELECT cc.continent, FLOOR(AVG(c.population)) pop
FROM City c
JOIN Country cc ON cc.code = c.countrycode
GROUP BY cc.continent
ORDER BY cc.continent

答案 2 :(得分:1)

SELECT cc.CONTINENT, cc.NAME, FLOOR(AVG(c.POPULATION)) AS population
FROM CITY c
INNER JOIN COUNTRY cc ON c.COUNTRYCODE = cc.CODE
GROUP BY cc.CONTINENT, cc.NAME
ORDER BY cc.CONTINENT, cc.NAME;

应该有效。我更喜欢对姓名等进行编码(但这取决于您和个人偏好):

SELECT `cc`.`CONTINENT`, `cc`.`NAME`, FLOOR(AVG(`c`.`POPULATION`)) AS `population`
FROM CITY `c`
INNER JOIN COUNTRY `cc` ON `c`.`COUNTRYCODE` = `cc`.`CODE`
GROUP BY `cc`.`CONTINENT`, `cc`.`NAME`
ORDER BY `cc`.`CONTINENT`, `cc`.`NAME`;