在同一表中使用不同搜索的Mysql查询
我想要做的是在具有两个不同值的表中搜索,这很难解释,所以我只举一个例子。在同一表中使用不同搜索的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%')
如果在所有可能的情况下,我想保留所有的动物行在同一个表中,所以我不必将它们分开。感谢您所有的帮助!
您需要多个表格查找,每个查找一个特定的动物。例如,使用一个双连接:
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%'
)
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%'))
如果某人为“(鸟,梗犬)”或“(狗,非洲灰色)”添加动物记录会发生什么? – Thomas 2010-08-12 18:44:47
根据两种条件的需求进行更改。 – websch01ar 2010-08-12 18:46:30
托马斯,我们可以在每次检查中添加额外的过滤器。我们只需要将两个检查都保存在一个()中。 – websch01ar 2010-08-12 18:48:07
删除我的,这是要走的路。误解了这个问题。 – 2010-08-12 18:45:06
不知道你能做到这一点,你知道女巫方法更快吗? – Scott 2010-08-12 19:01:52
@Scott:他们应该或多或少地相当。如果您需要从动物表中选择字段,只有第一个查询有效 – Andomar 2010-08-12 19:05:03