一些我不知道该怎么写的选择

时间:2019-04-29 17:08:08

标签: mysql sql

我是SQL的新手,所以如果我问愚蠢的问题,请原谅我。

我有三个表,一个与国家/地区在一起,一个与城市(与国家相连,人口...),另一个与语言(也与国家相连)。

我想向MySQL询问以下信息:

  1. 所有城市的居民超过100000的国家/地区的名称,
  2. 在“城市”表中至少有一个城市的国家/地区的名称,
  3. 说英语但不说英语的国家/地区的名称

,依此类推。我开始了解接合点,并进行了一些分组,但这仅是全部。

2 个答案:

答案 0 :(得分:1)

第一个查询

SELECT name FROM country WHERE id IN 
    (SELECT big_city.country_id FROM 
                  (SELECT country_id, COUNT(*) as n FROM city WHERE population > 100000 GROUP BY country_id) as big_city,
                  (SELECT country_id, COUNT(*) as n FROM city GROUP BY country_id)  
    as all_city WHERE big_city.country_id = all_city.country_id AND big_city.n = all_city.n)

我在子查询中正在做的是列出所有注册城镇的人口都超过10万人的国家/地区。

第二个查询

SELECT country.name FROM country WHERE country.id IN (SELECT DISTINCT country_id FROM city);

这样做会在city表中获得所有国家/地区ID,因此您可以以此为条件

第三次查询

SELECT country.name FROM country WHERE country.id IN 
    (SELECT DISTINCT country_id FROM language WHERE language = "en")
    AND NOT country.id IN (SELECT DISTINCT country_id FROM language WHERE language = "es")

与以前一样,您获取说英语或西班牙语的所有国家/地区并进行相应过滤

答案 1 :(得分:1)

提供更多详细信息,例如表和数据库版本: 如果您在SQLServer 2017中考虑以下脚本:

create table countries
(
    [id] int not null identity,
    [name] varchar(100) not null,

    constraint pk_countries primary key ([id])
)
insert into countries ([name]) values ('Country 1'), ('Country 2'), ('Country 3')

create table cities
(
    [id] int not null identity,
    [idCountry] int not null,
    [name] varchar(100) not null,
    [population] int not null,

    constraint pk_cities primary key ([id]),
    constraint fk_cities_countries foreign key ([idCountry]) references countries ([id])
)
insert into cities ([idCountry], [name], [population]) values 
    (1, 'City 11', 1500000), (1, 'City 22', 2000000),
    (2, 'City 21', 2000000), (2, 'City 22', 100)

create table languages
(
    [id] int not null identity,
    [idCity] int not null,
    [name] varchar(100) not null,

    constraint pk_languages primary key ([id]),
    constraint fk_languages_cities foreign key ([idCity]) references cities ([id])
)
insert into languages ([idCity], [name]) values (1, 'Lang 1'), (1, 'Lang 2'), (1, 'Lang 3')


-- the names of the countries for which all the cities have more than 100000 citizen
select 
  distinct (a.name)
from
  countries a
where
  not exists (select * from cities where idCountry = a.id and population < 1000000) and
  exists (select * from cities where idCountry = a.id)

go

-- the names of the countries for which at least one city is in the cities table,
select 
  distinct (a.name)
from
  countries a
where
  exists (select * from cities where idCountry = a.id)

结果(http://www.sqlfiddle.com/#!18/326e0/1):

Country1

Country 1
Country 2