MySQL单表,基于多行选择值

MySQL单表,基于多行选择值,mysql,sql,Mysql,Sql,从下表中,我将如何选择所有具有特定属性组合的动物,例如,如果我提供了属性455和685,我将期望获得动物55和93 表名:动物属性 id attributeId animalId 1 455 55 2 233 55 3 685 55 4 999 89 5 455 89 6 333

从下表中,我将如何选择所有具有特定属性组合的动物,例如,如果我提供了属性455和685,我将期望获得动物55和93

表名:动物属性

id      attributeId     animalId
1       455             55
2       233             55
3       685             55
4       999             89
5       455             89
6       333             93
7       685             93
8       455             93
我有下面的查询,似乎是可行的,但是,我不确定是否有一个更强大的方法

  SELECT animalId
    FROM animalAttributes
   WHERE attributeId IN (455,685)
GROUP BY animalId 
  HAVING COUNT(DISTINCT attributeId) = 2;


如果你真的想得到准确的结果,你可以用这样一种简单的方法:

select distinct base.animalId
from animalAttributes base
join animalAttributes a on base.animalId = a.animalId
     and a.attributeId = 455
where base.attributeId = 685
如果以后需要3个匹配属性,则可以添加另一个连接:

select distinct base.animalId
from animalAttributes base
join animalAttributes a on base.animalId = a.animalId
     and a.attributeId = 455
join animalAttributes b on base.animalId = b.animalId
     and b.attributeId = 999
where base.attributeId = 685

这将返回animalid,即使它们只有一个attributeId值。@MarkD-它需要基于455和685的组合,而不是455或685。我猜你的查询会返回animalIds 55,89,93?我想这个查询不会给出你想要的。可以想象,一种动物有455个属性,另一种,比如说,有123个属性。这将返回,因为它有两个。123不在条件中,因此不包括在内。没有必要让子句
Having COUNT(DISTINCT attributeId)=2
Having子句确保它们同时具有两个属性。这个查询在我看来还可以。我认为如果(attributeId,animalId)是唯一的,那么您不需要使用DISTINCT。当您说“傻瓜证明”时,它如何更健壮?Thanks@raider5他说,这是针对老年退休金计划(OPs)的问题,他说“似乎有效”。此外,其他一些答案也没有给我它们将起作用的温暖的模糊性。
select distinct base.animalId
from animalAttributes base
join animalAttributes a on base.animalId = a.animalId
     and a.attributeId = 455
where base.attributeId = 685
select distinct base.animalId
from animalAttributes base
join animalAttributes a on base.animalId = a.animalId
     and a.attributeId = 455
join animalAttributes b on base.animalId = b.animalId
     and b.attributeId = 999
where base.attributeId = 685
SELECT DISTINCT `animalId` FROM `animalAttributes` WHERE `attributeId` = 455
INTERSECT
SELECT DISTINCT `animalId` FROM `animalAttributes` WHERE `attributeId` = 685