2011-11-30 48 views
3

我有如下表:SQL請求 - 多值

userid title   content 
1   gender  male 
1   location  NY  
2   gender  female 
2   location  SF 
3   gender  female 
3   location  NY 

我試圖用性別=「男」和位置=「NY」

,如果我嘗試僅檢索用戶ID :

select userid 
from table 
where content="male" 
    AND location="NY"; 

它將返回null。 任何想法如何做到這一點?

+0

順便說一句:這是一個表結構的壞主意。如果可能,我會建議重新構建它。 – JohnFx

+0

我知道,但它是這樣設計的。 – user7330

+0

我知道用遺留代碼卡住是什麼感覺。 –

回答

1
SELECT t.userId 
FROM yourTable AS t 
INNER JOIN yourTable AS t2 ON t.userId = t2.userId 
    AND t.title = 'gender' 
    AND t.content = 'male' 
    AND t2.title = 'location' 
    AND t2.content = 'NY' 

我也會考慮看看規範化你的數據。這將使這樣的查詢在未來更容易(也可能更快)。

+0

擊敗我35秒。恨這種事發生。需要學習如何更快地輸入這些壘球問題。 +1 – JohnFx

+0

@JohnFx我絕對知道這是怎麼回事,我今天已經在很多問題上太慢了。 –

+0

太棒了!非常感謝 – user7330