sql语句计算字段

cgvd09ve  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(314)

这是我的问题,最后一点我需要帮助。我不知道如何创建一个计算字段来计算字段名的含义。
从城市表中选择id、姓名、国家和人口,从国家表中选择预期寿命、姓名、地区和国民生产总值。使用以下条件限制结果集(要返回记录,必须满足以下所有条件):
国家地表面积介于3000000和40000000之间(使用
(操作员之间)
city.district字段的长度大于4
创建计算字段“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

国家表
城市表

11dmarpk

11dmarpk1#

好像是半交叉连接。也就是说,从 City 与从中返回的每一行匹配 Country .
我建议放弃join操作的老式逗号语法,并使用 JOIN 改为关键字。如果我们想要一个半笛卡尔积,我建议包括 CROSS 关键字来提醒将来的读者 ON 从句是故意的,不是疏忽。
此外,还有 LENGTH 函数返回字节数;使用 CHAR_LENGTH 返回字符数。
我怀疑我们想把每个城市与一个特定的国家“匹配”。也许是 City 表包含 Country_ID 列外键引用 ID 中的列 Country table。或者可能是 Country 列是外键(那只是猜测;没有确凿的迹象表明问题是这样的。)

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
inb24sb2

inb24sb22#

不要在句子中使用逗号 FROM 条款。始终使用适当的、明确的、标准的 JOIN 语法。您的查询应如下所示:

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

相关问题