假设我有下一张桌子
Table names
id | name
1 | mike
2 | john
3 | jack
Table attributes
name_id | skill
1 | css
1 | html
1 | php
2 | html
2 | java
2 | css
3 | java
我需要获取所有具有 css 和 html 属性的 id 和名称。我试过使用“JOIN”,但要搜索的属性数量可能不同。
我还没有尝试过其他任何东西,因为我不知道该尝试什么。
谢谢
尝试使用GROUP BY ...和HAVING COUNT(DISTINCT ...):
SELECT name_id
FROM attributes
WHERE skill IN ('css', 'html')
GROUP BY name_id
HAVING COUNT(DISTINCT skill) = 2
在线查看它:sqlfiddle
您可以加入以获取名称。
select names.id, names.name
from
names
inner join
attributes
on names.id = attributes.name_id
where skill in ('css','html')
group by names.id, names.name
having count(distinct skill) = 2 -- where 2 is the number of skills you are looking for