MySQL单表,根据多行选择值

时间:2011-05-31 23:33:02

标签: mysql sql

从下表中,我如何选择具有attributeIds特定组合的所有animalIds,例如如果我提供了attributeIds 455&我希望能找回动物玩具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;

3 个答案:

答案 0 :(得分:1)

SELECT DISTINCT animalId
FROM animalAttributes
WHERE attributeId IN (455,685)

SELECT animalId
FROM animalAttributes
WHERE attributeId IN (455,685)
GROUP BY animalId

答案 1 :(得分:1)

如果你真的想要准确的结果,你可以采用这样一种万无一失的方法:

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

答案 2 :(得分:1)

SELECT DISTINCT `animalId` FROM `animalAttributes` WHERE `attributeId` = 455
INTERSECT
SELECT DISTINCT `animalId` FROM `animalAttributes` WHERE `attributeId` = 685