1

我有基本的多对多关系集与表categorieslocationscategories_locations表。例子:

类别表

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

位置表

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

类别_位置表

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

如何获取属于第 2 类同时也属于第 3 类的所有位置?在上面的示例中,这只会导致位置 3!

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

4

1 回答 1

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
于 2012-08-24T10:46:47.317 回答