这是我的问题,我需要最后一个要点的帮助。我无法弄清楚如何创建一个计算字段来计算字段名称的含义。
从City表中选择ID,名称,国家和人口,并从Country表中选择Life Expectancy,Name,SurfaceArea,GNP。使用以下条件限制结果集(必须满足以下所有条件才能返回记录):
Country SurfaceArea介于3,000,000和40,000,000之间(使用
在运营商之间)
City.District字段的长度大于4
创建计算结果 field'CityPopulationPercentageOfCountryPopulation'计算 字段名称的含义。
这是我到目前为止所拥有的。提前致谢。
SELECT City.ID
, City.name
, City.Country
, City.Population
, Country.LifeExpectancy
, Country.Name
, Country.SurfaceArea
, Country.GNP
, ROUND(City.Population * 100.0 / Country.Population, 1) AS 'CityPopulationPercentageOfCountryPopulation'
FROM City
, Country
WHERE Country.SurfaceArea BETWEEN 3000000 AND 40000000
AND LENGTH(City.District) > 4
答案 0 :(得分:0)
Never use commas in the FROM
clause. Always use proper, explicit, standard JOIN
syntax. Your query should look like this:
SELECT . . .
FROM City JOIN
Country
ON City.CountryCode = Country.Code -- or whatever columns are used for the `JOIN`
WHERE Country.SurfaceArea BETWEEN 3000000 AND 40000000 AND
LENGTH(City.District) > 4
答案 1 :(得分:0)
Seems like a semi-cross join here. That is, every row returned from City
is matched with every row returned from Country
.
I recommend ditching the old school comma syntax for the join operation, and use the JOIN
keyword instead. If we're intending a semi-Cartesian product, I'd recommend including the CROSS
keyword to alert future readers that the omission of any join predicates (conditions to match on) in the ON
clause is intentional, and not an oversight.
Also, the LENGTH
function returns number of bytes; use CHAR_LENGTH
to return a count of characters.
I suspect we want to "match" each City to a particular Country. Maybe the City
table contains a Country_ID
column foreign key referencing ID
column in the Country
table. Or maybe the Country
column is the foreign key. (That's just a guess; there's no conclusive indication this is the case in the question.)
SELECT ci.ID AS city_id
, ci.name AS city_name
, ci.Country AS city_country
, ci.Population AS city_population
, co.LifeExpectancy AS country_lifeexpectancy
, co.Name AS country_name
, co.SurfaceArea AS country_surfacearea
, co.GNP AS country_gnp
, ROUND(100 * ci.Population / co.Population, 1) AS `CityPopulationPercentageOfCountryPopulation`
FROM City ci
JOIN Country co
ON co.ID = ci.Country_ID
WHERE co.SurfaceArea BETWEEN 3000000 AND 40000000
AND CHAR_LENGTH(ci.District) > 4