繁体   English   中英

MySQL单表,select值基于多行

[英]MySQL single table, select value based on multiple rows

从下表中,我将如何 select 所有具有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 animalId
FROM animalAttributes
WHERE attributeId IN (455,685)

或者

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM