SQL过滤器从多对多关系

时间:2012-08-24 10:41:47

标签: sql many-to-many relational-database

我有基本的多对多关系集,表categorieslocations通过categories_locations表。例如:

分类表

| ID | Name       |
| 1  | Category 1 |
| 2  | Category 2 |
| 3  | Category 3 |

地点信息表

| ID | Name       |
| 1  | Location 1 |
| 2  | Location 2 |
| 3  | Location 3 |

Categories_Locations表

| category_id | location_id |
| 1           | 1           |
| 2           | 2           |
| 2           | 3           |
| 3           | 1           |
| 3           | 3           |

如何获得属于第2类的所有位置同时也属于第3类?在上面的例子中,只会产生位置3!

使用OR过滤很简单。只是一个普通的左连接,其中category_id IN(匹配的类别)。但是当我想要只获得属于category1且同时也属于category2(等等)的那些关系时,如何过滤?

1 个答案:

答案 0 :(得分:4)

select 
    Location_ID 
from CategoryLocations
where Category_ID in (2,3)
group by Location_ID
having COUNT(distinct Category_ID) = 2  -- this 2 is the number of items in the IN list above