我有一个表item_category有两列:item_id,cat_id.项目与类别是多对多关系.
如果我的桌子看起来像这样......
item_id | cat_id
1 | 1
1 | 2
2 | 3
2 | 4
3 | 5
3 | 6
4 | 7
4 | 8
5 | 9
5 | 10
Run Code Online (Sandbox Code Playgroud)
...我怎样才能选择一个不同的列表item_ids表示没有任何地方行category_id是2或7(产生item_id的2秒,3,5)?
我会使用聚合和一个having子句来做到这一点:
select item_id
from item_category ic
group by item_id
having max(cat_id = 2) = 0 and
max(cat_id = 7) = 0
Run Code Online (Sandbox Code Playgroud)
这是"set-within-sets"查询的示例.使用group bywith having是此类查询的最通用形式.例如,如果您想确保包含类别3,则可以将该having子句更改为:
having max(cat_id = 2) = 0 and
max(cat_id = 7) = 0 and
max(cat_id = 3) = 1
Run Code Online (Sandbox Code Playgroud)