mysql - NxM表查询

标签 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

我想要一个只返回同时拥有狗和猫的所有者的查询,在本例中是 carly。宠物的数量可能不止这两个。

最佳答案

有几种方法可以做到这一点,包括使用两个 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

关于mysql - NxM表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38160093/

相关文章:

mysql - 选择列值为 1 而不是 4 的人

mysql - 根据 Null 或 Not Null 值删除重复项

php - 如何将 PHP 变量插入到 SQL 查询中

php - 下拉列表未在 IE 中填充?

sql - 从在 DB2 中使用 WITH 子句的 Select 查询插入故事

mysql - 在本地下载远程数据库并从该 mysql 转储文件创建一个新数据库

php - 在Android(模拟器)中连接服务器数据库

MySQL 服务器在导入一个巨大的数据库时已经消失了异常

java - 如何存储大型Java对象/多维数组?

mysql - 表更新为相同值