在同一个表中使用不同搜索的Mysql查询

时间:2010-08-12 18:36:41

标签: sql 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(Bob)和2(Jack)。

我已经尝试过基本的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%' )

如果可能的话,我想把所有的动物排在同一张桌子上,这样我就不必将它们分开了。感谢您的所有帮助!

2 个答案:

答案 0 :(得分: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%'
        )

答案 1 :(得分: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%'))