Php 如何在mysql中搜索?
如何选择能力为1、2和3的医生id? (所以答案是70) 我知道我不能用在陈述中Php 如何在mysql中搜索?,php,mysql,search,many-to-many,Php,Mysql,Search,Many To Many,如何选择能力为1、2和3的医生id? (所以答案是70) 我知道我不能用在陈述中 doctor_id| ability_id -------- | ------------- 70 | 1 71 | 2 70 | 2 70 | 3 50 | 1 20 | 2 10 | 2 您可以使用分组依据和拥有: select doctor_id from
doctor_id| ability_id
-------- | -------------
70 | 1
71 | 2
70 | 2
70 | 3
50 | 1
20 | 2
10 | 2
您可以使用
分组依据
和拥有
:
select doctor_id
from t
group by doctor_id
having sum(ability_id = 1) > 0 and
sum(ability_id = 2) > 0 and
sum(ability_id = 3) > 0 ;
“不在中使用”是一个非常奇怪的要求。更自然的书写方式是:
select doctor_id
from t
where ability_id in (1, 2, 3)
group by doctor_id
having count(*) = 3;
Gordon查询的另一种方法是按医生聚合,限制为1、2或3中的能力,然后保留那些具有三种不同能力的医生。这意味着留任医生具备所有三种能力
SELECT doctor_id
FROM yourTable
WHERE ability_id IN (1, 2, 3)
GROUP BY doctor_id
HAVING COUNT(DISTINCT ability_id) = 3
考虑到这个问题,答案应该是70是很奇怪的。这是正确的,但如果我将最后一行改为COUNT(*)=3,那么我为什么要在这里使用distinct,@faezehrasouli如果给定的医生可以为给定的能力有多个记录,那么使用COUNT(*)
将给出假阳性。例如,如果医生有1、1、2,那么COUNT(*)将报告3,这是错误的。如果您确定某个技能只能为给定的医生出现一次,则只需COUNT(*)就可以了,但使用COUNT
和DISTINCT
总是正确的。