我的询问的目标是返回所说的语言的国家,资本和数量。它还需要按递减的语言数量排序,然后按资本排序。最后,语言数量必须至少为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号和名称。
如果有人能发现我的错误,我将非常感激!
答案 0 :(得分:4)
您错过了与countrylanguage
的关系。没有它,你有一个笛卡尔积,所以Count(countrylanguage.language)
等于countrylanguage
中的记录数,最有可能大于10。
这是一个建议的解决方案(相应地调整字段名称/ DB结构):
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