我试图返回一份清单,列出人口大于世界平均人口的每个国家的名字,以及我的数据库中世界平均数与该国人口之间的差异:
国家/地区数据库的格式如下: 代码,名称,大陆,地区,SurfaceArea,IndepYear,人口,LifeExpectancy,GNP,GNPOld,LocalName,GovernmentForm,HeadOfState,Capital,Code2
到目前为止,我已经提出了这段代码:
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`@`localhost`
SQL SECURITY DEFINER
VIEW `average_population` AS
SELECT
`country`.`Code` AS `code`,
`country`.`Name` AS `name`,
`country`.`Continent` AS `continent`,
`country`.`Region` AS `region`,
`country`.`Population` AS `population`
FROM
`country`
GROUP BY code
HAVING AVG(population) > (SELECT AVG(Population)
FROM country)
如果我在第一个选择语句中设置AVG(填充),这只返回一个记录?
我如何获得人口大于世界平均人口的每个国家的名单,以及我的数据库中世界平均数与该国人口之间的差异?
答案 0 :(得分:0)
尝试在单独的查询中计算世界人口。
SELECT
`country`.`Code` AS `code`,
`country`.`Name` AS `name`,
`country`.`Continent` AS `continent`,
`country`.`Region` AS `region`,
`country`.`Population` AS `population`
FROM
`country`
CROSS JOIN (SELECT AVG(Population) AS everyone FROM country) as World
GROUP BY code
HAVING AVG(population) > World.everyone
答案 1 :(得分:0)
如果您需要在一行中执行此操作,则可以使用嵌套选择。
<div class="panel-group">
如果可能,如果您事先计算并存储平均值,效率会更高。这样您就不需要为每一行运行平均函数。