MySQL单表,根据多行选择值

问题描述

| 从下表中,我将如何选择具有attributeIds特定组合的所有animalIds,例如如果我提供了attributeIds 455和685,我希望可以取回animalIds 55和93 表名:animalAttributes
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
    ,        
SELECT DISTINCT `animalId` FROM `animalAttributes` WHERE `attributeId` = 455
INTERSECT
SELECT DISTINCT `animalId` FROM `animalAttributes` WHERE `attributeId` = 685
    ,        
SELECT DISTINCT animalId
FROM animalAttributes
WHERE attributeId IN (455,685)
要么
SELECT animalId
FROM animalAttributes
WHERE attributeId IN (455,685)
GROUP BY animalId