MYSQL:通过连接多个表来查询世界数据库

问题描述 投票:0回答:2

问题是:

给出要显示北美每个国家/地区的 SQL 命令:

  • 首都名称
  • 国家名称
  • 官方语言
  • 讲官方语言的人口百分比

结果应按城市名称字母顺序排列,按国家名称顺序排列,按语言顺序排列,按百分比升序排列。收到错误消息不是唯一的表别名国家/地区。

SELECT
  city.name AS name, country.name AS name,
  countrylanguage.language, 
  countrylanguage.percentage
FROM country, countrylanguage, city
INNER JOIN country ON city.countrycode = country.code
INNER JOIN city ON country.capital = city.id
INNER JOIN countrylanguage on country.code = countrylanguage.countrycode
WHERE
  country.continent = 'North America' and
  countrylanguage.isofficial = 'T' and 
  country.capital = city.id
ORDER BY
  city.name ASC,
  country.name,
  country.language,
  countrylanguage.percentage ASC;
mysql inner-join
2个回答
1
投票

您查询的

FROM ... JOIN 
部分不正确。试试这个。

SELECT
  city.name AS name, country.name AS name,
  countrylanguage.language, 
  countrylanguage.percentage
FROM country
INNER JOIN country ON city.countrycode = country.code
INNER JOIN city ON country.capital = city.id
INNER JOIN countrylanguage on country.code = countrylanguage.countrycode
WHERE
  country.continent = 'North America' and
  countrylanguage.isofficial = 'T' and 
  country.capital = city.id
ORDER BY
  city.name ASC,
  country.name ASC,
  country.language ASC,
  countrylanguage.percentage ASC;

当您说

FROM country, city, countrylanguage
时,它与上面的代码等效,但没有
ON
子句。这是老式的逗号连接语法(1992 年被显式 JOIN 语法取代)。


0
投票

试试这个:

SELECT
  city.name AS city, country.name AS country, -- change the alias for better column identification.
  countrylanguage.language, 
  countrylanguage.percentage
FROM country
INNER JOIN city ON city.countrycode = country.code AND country.capital = city.id -- Use AND instead of another INNER JOIN call for the same table (city).
INNER JOIN countrylanguage on country.code = countrylanguage.countrycode
WHERE
  country.continent = 'North America' and
  countrylanguage.isofficial = 'T' and 
  country.capital = city.id
ORDER BY
  city.name ASC,
  country.name,
  countrylanguage.language, -- The Language column belongs to the countrylanguage table, not the country table.
  countrylanguage.percentage ASC;
© www.soinside.com 2019 - 2024. All rights reserved.