Mysql 限制表中某列中具有特定值的记录数
我的任务是选择城市数量高于表中加拿大城市数量的国家。我正在使用萨基拉数据库中的城市和国家表。现在,我有了这样的东西:Mysql 限制表中某列中具有特定值的记录数,mysql,sql,Mysql,Sql,我的任务是选择城市数量高于表中加拿大城市数量的国家。我正在使用萨基拉数据库中的城市和国家表。现在,我有了这样的东西: SELECT country, COUNT(country) FROM ( city INNER JOIN country ON country.country_id = city.country_id) GROUP BY country HAVING COUNT(country) >= 7 -- should be COUNT(country='Canada'
SELECT country, COUNT(country) FROM ( city
INNER JOIN country ON country.country_id = city.country_id)
GROUP BY country
HAVING COUNT(country) >= 7 -- should be COUNT(country='Canada') or something like that
ORDER BY COUNT(country) DESC;
第四行的第7位是城市数量,其中国家栏等于“加拿大”,但我不知道如何使用SQL计算,也找不到使用谷歌的正确方法。有什么建议吗?您需要在HAVING子句中添加一个子查询 以下查询获取加拿大的城市数
SELECT count(*)
FROM city
LEFT JOIN country ON city.country_id = country.country_id
WHERE country = 'Canada'
GROUP BY country
所以你把这个放在having子句中
SELECT
country, COUNT(*)
FROM
city
INNER JOIN
country ON country.country_id = city.country_id
GROUP BY
country
HAVING
COUNT(country) >= (
SELECT count(*)
FROM city
LEFT JOIN country ON city.country_id = country.country_id
WHERE country = 'Canada'
GROUP BY country
)
ORDER BY
COUNT(country) DESC;
有计数(国家=‘加拿大’则1结束时的情况)>=7