2017-10-05 12 views
0

對於兩列;人和衣服;MySQL - 選擇基於一列中的重複會議需求的另一個

person clothing 
A   shirt 
B   shoes 
A   pants 
A   shoes 

如何選擇只有誰擁有這三種類型的服裝(上衣,褲子和鞋子)的人給予回覆:

person 
A 

編輯:我不知道是否有某種迭代可以做

return person if for (i=0, i<number of rows, i++) all three types are found.

回答

2

另一種解決方案(未例如花式作爲Gordon的一個)是利用某種MySQL的交點。

SELECT DISTINCT pc.person 
FROM personclothing pc 
INNER JOIN personclothing pc2 on pc.person = pc2.person AND pc2.clothing = 'shirt' 
INNER JOIN personclothing pc3 on pc.person = pc3.person AND pc3.clothing = 'pants' 
INNER JOIN personclothing pc4 on pc.person = pc4.person AND pc4.clothing = 'shoes' 

或使用基於評論IN

SELECT pc.person 
FROM personclothing 
WHERE person IN (SELECT person FROM personclothing WHERE clothing = 'shirt') AND 
     person IN (SELECT person FROM personclothing WHERE clothing = 'pants') AND 
     person IN (SELECT person FROM personclothing WHERE clothing = 'shoes') 

編輯。如果你需要有shirt和其中的一個人:pantsshoes

SELECT pc.person 
FROM personclothing 
WHERE person IN (SELECT person FROM personclothing WHERE clothing = 'shirt') AND 
    (  
     person IN (SELECT person FROM personclothing WHERE clothing = 'pants') OR 
     person IN (SELECT person FROM personclothing WHERE clothing = 'shoes') 
    ) 
+0

謝謝!你知道我可以在這裏爲「OR」做些什麼嗎?例如:這個人有一件襯衫和褲子或鞋子 –

+1

@GabrielVega在第二種解決方案中絕對有可能。查看編輯。 –

2

一種方法是:

select person 
from personclothing 
where clothing in ('shirt', 'pants', 'shoes') 
group by person 
having count(distinct clothing) = 3; 

如果您沒有重複項,則使用count(*)而不是count(distinct)

+0

謝謝!忽略編輯太快 –

1

另一種方法是:

select 
person, 
count(distinct(clothing)) as clothing_count 
from 
personclothing 
where 
clothing in ('shirt', 'pants', 'shoes') 
group by 
person 
having 
clothing_count = 3; 
+0

雖然這會在結果集中給出額外的列。您可以忽略該欄。 –

相關問題