NxM表查询

时间:2016-07-02 12:20:51

标签: mysql database select

为了解决我的问题,请考虑以下三个表:#

人:

personid int auto_increment not null,
firstname varchar(16) not null,
constraint pk_person primary key (personid)

宠物:

petid int auto_increment not null,
petname varchar(16) not null,
constraint pk_pet primary key (petid)

所有权:

owner int not null,
pet int not null,
constraint fk_owner_ownership foreign key (owner) references Person (personid) on delete cascade,
constraint fk_pet_ownership foreign key (pet) references Pet (petid) on delete cascade,
constraint pk_ownership primary key (owner, pet)

和元组:

insert into person (firstname) values ("andy");
insert into person (firstname) values ("barney");
insert into person (firstname) values ("carly");

insert into pet (petname) values ("dog");
insert into pet (petname) values ("cat");

insert into ownership (owner, pet) values (1, 1); #andy owns a dog
insert into ownership (owner, pet) values (2, 2); #barney owns a cat
insert into ownership (owner, pet) values (3, 1);
insert into ownership (owner, pet) values (3, 2); #carly owns a dog and a cat

我想要一个只返回拥有狗和猫的所有者的查询,在这种情况下,它是卡利的。宠物的数量可能超过这两个。

1 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点,包括使用两个exists条件。不过,我个人最喜欢的是查询哪些业主有猫或狗,并计算他们拥有的宠物数量:

SELECT   firstname
FROM     person psn
JOIN     ownership o ON psn.personid = o.owner
JOIN     pet ON pet.petit = o.pet
WHERE    petname IN ('dog', 'cat')
GROUP BY firstname
HAVING   COUNT(DISTINCT petname) = 2