假设我有下一张表
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
我需要获取所有id和名称,例如css和html属性。我尝试使用“JOIN”但搜索的属性数量可能不同。
我还没有尝试过任何其他因为我无法弄清楚要尝试什么。
谢谢
答案 0 :(得分:4)
尝试使用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
您也可以加入以获取姓名。
答案 1 :(得分:3)
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