选择与相关表中的多个行匹配的行

时间:2012-05-17 10:04:24

标签: mysql select

我有三张桌子:

项目

id   name   etc
--------------------
1    Rex   
2    Fido
3    Geoff

类别

id   name
------------
1    Dogs
2    Humans
3    Mammals

category_item

category_id  item_id
--------------------
1            1
3            1
1            2
3            2
2            3
3            3

我还有一系列类别ID。我想计算与数组中所有类别相关的项目数。

例如......

Category_ids    Result
----------------------
1,2             0
2,3             1
1,2,3           0

当我想出这个时,我很确定我会踢自己。

1 个答案:

答案 0 :(得分:2)

请尝试下面给出的查询..

select count(*) AS Result from (
         SELECT count(item_id) FROM category_item
                             WHERE 
                            category_id in (2 ,3)
                            GROUP by item_id 

                              HAVING count(*) = 2
                             ) AS temp

在此查询put count(*) value equal to total number of category_id for example if you are checking for category_ids 1,2,3 then put having count(*) = 3中。在此查询中,假设您提供category_id 1和2,然后它将使用

获取item_id的总存在数量

我希望此查询对您有所帮助。

感谢