2012-09-26 14 views
2

讓我們假設我有下表MySQL的:使用不同的參數獲取行

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」,但要搜索的屬性數量可能不同。

我沒有嘗試過其他任何東西,因爲我無法弄清楚要嘗試什麼。

謝謝

回答

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

謝謝。我已經投了兩個答案,但我選擇這個因爲小提琴的例子。 – keepwalking

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