1

我查询的目标是返回国家、首都和使用的语言数量。它还需要按使用的语言数量降序排列,然后按大写字母排序。最后,语言的数量必须至少为 5 和 10 或更少。

这是我的查询:

SELECT country.name                    AS Country,
       city.name                       AS Capital,
       Count(countrylanguage.language) AS NumLanguages
FROM   country,
       city,
       countrylanguage
WHERE  city.id = country.capital
GROUP  BY city.name,
          country.name
HAVING ( Count(countrylanguage.language) BETWEEN 5 AND 10 ); 

它什么也不返回。where 子句对于显示城市名称是必要的。country 表中只是一个 id 号,然后 city 表中保存了 id 号和名称。

如果有人能发现我的错误,我将不胜感激!

4

1 回答 1

4

您缺少与 的关系countrylanguage。没有它,你有一个笛卡尔积,所以Count(countrylanguage.language)等于 中的记录数,countrylanguage很可能大于 10。

这是一个建议的解决方案(相应地调整字段名称/数据库结构):

SELECT country.name                    AS Country,
       city.name                       AS Capital,
       Count(countrylanguage.language) AS NumLanguages
FROM   country,
       city,
       countrylanguage
WHERE  city.id = country.capital
AND    countrylanguage.language_id = country.language_id
GROUP  BY city.name,
          country.name
HAVING ( Count(countrylanguage.language) BETWEEN 5 AND 10 )
ORDER BY NumLanguages desc, city.Name

也就是说,您应该始终尽量避免WHERE查询子句中的连接(隐式连接)。偏爱显式(声明性)连接将为您提供更高的可读性和更大的灵活性。

更新

根据评论建议,这里是使用 ANSI-92 连接语法的查询版本:

SELECT country.name                    AS Country,
       city.name                       AS Capital,
       Count(countrylanguage.language) AS NumLanguages
FROM       country
INNER JOIN city on city.id = country.capital
INNER JOIN countrylanguage on countrylanguage.language_id = country.language_id
GROUP  BY city.name,
          country.name
HAVING ( Count(countrylanguage.language) BETWEEN 5 AND 10 ); 
ORDER BY NumLanguages desc, city.Name
于 2012-09-17T20:47:35.923 回答