在连接表中选择具有一个特定条目(但不是另一个特定条目)的元组

时间:2014-04-11 22:58:26

标签: sql

鉴于以下数据定义:

create table vikings(
  name varchar(256));

create table countries(
  name varchar(256));

create table homes(
  viking varchar(256),
  country varchar(256));

INSERT INTO vikings VALUES ('Rollo');
INSERT INTO vikings VALUES ('Floki');
INSERT INTO vikings VALUES ('Egill');
INSERT INTO vikings VALUES ('Eirikr');

INSERT INTO countries VALUES ('Iceland');
INSERT INTO countries VALUES ('Norway');
INSERT INTO countries VALUES ('Sweden');
INSERT INTO countries VALUES ('Faroes');

INSERT INTO homes VALUES ('Rollo', 'Norway');
INSERT INTO homes VALUES ('Floki', 'Norway');
INSERT INTO homes VALUES ('Floki', 'Sweden');
INSERT INTO homes VALUES ('Egill', 'Iceland');
INSERT INTO homes VALUES ('Egill', 'Sweden');
INSERT INTO homes VALUES ('Eirikr', 'Iceland');
INSERT INTO homes VALUES ('Eirikr', 'Faroes');

我如何在SQL中使用以下查询?

"给我所有在挪威或冰岛有家的维京人,但不包括瑞典或法罗群岛"

我已经设置了一个SQLFiddle,可以在这里播放:http://sqlfiddle.com/#!2/aea39b/2

1 个答案:

答案 0 :(得分:1)

你想要的基本上是一组差异。显示在挪威或冰岛拥有房屋的一组维京人的所有成员,并减去在法罗群岛瑞典拥有房屋的一组维京人。

您的SQL Fiddle设置为使用MySQL,我相信它不支持except运算符,但通常这些查询中的任何一个都应该给出相同的结果:

select viking from homes where country in ('Norway', 'Iceland')
except
select viking from homes where country in ('Sweden', 'Faroes')

select viking from homes 
where country in ('Norway', 'Iceland')
and viking not in (
    select viking from homes where country in ('Sweden', 'Faroes')
    ) 

两个查询都将Rollo作为单个匹配。