假设我有两个表——people
和 pets
——每个人可能有不止一只宠物:
人
:
+-----------+-------+
| person_id | name |
+-----------+-------+
| 1 | Bob |
| 2 | John |
| 3 | Pete |
| 4 | Waldo |
+-----------+-------+
宠物
:
+--------+-----------+--------+
| pet_id | person_id | animal |
+--------+-----------+--------+
| 1 | 1 | dog |
| 2 | 1 | dog |
| 3 | 1 | cat |
| 4 | 2 | cat |
| 5 | 3 | dog |
| 6 | 3 | tiger |
| 7 | 3 | tiger |
| 8 | 4 | tiger |
| 9 | 4 | tiger |
| 10 | 4 | tiger |
+--------+-----------+--------+
我正在尝试选择只拥有老虎
作为宠物的人。显然,唯一符合此标准的是 Waldo
,因为 Pete
也有一只 dog
...但我在编写时遇到了一些问题对此的查询。
最明显的例子是select people.person_id, people.name from people join pets on people.person_id = pets.person_id where pets.animal = "tiger"
,但这返回皮特
和沃尔多
。
如果有像 pets.animal ONLY = "tiger"
这样的子句会很有帮助,但据我所知这并不存在。
如何编写查询?
最佳答案
select people.person_id, people.name
from people
join pets on people.person_id = pets.person_id
where pets.animal = "tiger"
AND people.person_id NOT IN (select person_id from pets where animal != 'tiger');
关于mysql - 选择外行仅匹配单个值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32036849/