MYSQL选择计数关系除法

时间:2013-02-27 14:30:22

标签: mysql sql relational-division

我在mysql中有这个表 enter image description here  1.是否可以选择一个计数 - 所有相同的entity_id,其中field_tags_tid = 2和field_tags_tid = 7

在此示例中,结果为1,因为只有entity_id = 6匹配field_tags_tid = 2且field_tags_tid = 7

1 个答案:

答案 0 :(得分:4)

此问题通常称为Relational Division

SELECT  entity_ID
FROM    tableName
WHERE   field_tags_ID IN (2,7)
GROUP   BY entity_ID
HAVING  COUNT(*) = 2

如果field_tags_IDentity_ID每个DISTINCT强制执行唯一性,则需要SELECT entity_ID FROM tableName WHERE field_tags_ID IN (2,7) GROUP BY entity_ID HAVING COUNT(DISTINCT field_tags_ID) = 2 个关键字。否则,保持原样,

SELECT  COUNT(*) totalCOunt
FROM
(
    SELECT  entity_ID
    FROM    tableName
    WHERE   field_tags_tid IN (2,7)
    GROUP   BY entity_ID
    HAVING  COUNT(DISTINCT field_tags_tid) = 2
) s

更新1

{{1}}