2010-08-12 37 views
2

我想要做的是在具有兩個不同值的表中搜索,這很難解釋,所以我只舉一個例子。在同一表中使用不同搜索的Mysql查詢

表:人

+----------------+ 
| id  name | 
|----------------| 
| 1  Bob  | 
| 2  Jack | 
| 3  Waly | 
| 4  Alex | 
++++++++++++++++++ 

表:動物

+------------------------------------------+ 
| id person key   value  | 
|------------------------------------------| 
| 1 1   dog   Terrier  | 
| 2 1   dog   Shepherd  | 
| 3 1   bird   African Grey | 
| 4 3   cat   Toyger  | 
| 5 3   cat   Korat  | 
| 6 2   dog   Terrier  | 
++++++++++++++++++++++++++++++++++++++++++++ 

例如:我希望能夠選擇只是有一個狗是人一隻小獵犬和一隻非洲鳥,所以它應該返回1(鮑勃)。我需要能夠添加和刪除參數我可能只想讓擁有梗犬的人返回1(鮑勃)和2(傑克)。

我試過基本的SQL,但已經得到它的工作,因爲當你限制的關鍵你可以搜索另一個。以下查詢是我嘗試過的,我想返回:1(Bob)。

SELECT p.id, p.name 
FROM people p, animals a 
WHERE p.id = a.person 
AND (a.key = 'dog' AND a.value LIKE '%Terrier%') 
AND (a.key = 'bird' AND a.value LIKE '%African%') 

如果在所有可能的情況下,我想保留所有的動物行在同一個表中,所以我不必將它們分開。感謝您所有的幫助!

回答

5

您需要多個表格查找,每個查找一個特定的動物。例如,使用一個雙連接:

select * 
from people p 
join animals a1 
on  a1.person = p.id 
join animals a2 
on  a2.person = p.id 
where a1.key = 'dog' and a1.value like '%Terrier%' 
     and a2.key = 'bird' and a2.value like '%African%' 

或雙存在:

select * 
from people p 
where exists 
     (
     select * 
     from animals a 
     where a.person = p.id 
       and a.key = 'dog' 
       and a.value like '%Terrier%' 
     ) 
     and exists 
     (
     select * 
     from animals a 
     where a.person = p.id 
       and a.key = 'bird' 
       and a.value like '%African%' 
     ) 
+0

刪除我的,這是要走的路。誤解了這個問題。 – 2010-08-12 18:45:06

+0

不知道你能做到這一點,你知道女巫方法更快嗎? – Scott 2010-08-12 19:01:52

+0

@Scott:他們應該或多或少地相當。如果您需要從動物表中選擇字段,只有第一個查詢有效 – Andomar 2010-08-12 19:05:03

0
Select p.id, p.name 
from people p 
INNER JOIN animals a on p.id = a.person 
WHERE ((a.key ='dog' and a.value Like '%Terrier%') and (a.key = 'bird' and a.value Like '%African Grey%')) 
+0

如果某人爲「(鳥,梗犬)」或「(狗,非洲灰色)」添加動物記錄會發生什麼? – Thomas 2010-08-12 18:44:47

+0

根據兩種條件的需求進行更改。 – websch01ar 2010-08-12 18:46:30

+0

托馬斯,我們可以在每次檢查中添加額外的過濾器。我們只需要將兩個檢查都保存在一個()中。 – websch01ar 2010-08-12 18:48:07

相關問題