2

很难说出这个问题,但下面是一个表格来说明我的问题。

Id   itemID   categoryID
1      5         10
2      5         16
3      6         10
4      2         10

如果我有这样的表设置,并且我想选择 categoryID 等于 10 和 16 的“itemID”,结果应该是 itemID 5。更多的上下文将是用户有一个属于 categoryID 的复选框列表,并且如果他们只选择 categoryID 10,则会出现 itemID 5、2 和 6。如果他们还选择 categoryID 16,则只会出现 itemID 5,因为它具有类别 10 和 16,而 itemID 2 仅具有类别 10。

4

2 回答 2

4

这是“set-within-sets”子查询的一个示例。我认为解决这些问题的最通用方法是使用聚合和having子句:

select itemID
from t
group by itemId
having sum(case when categoryID = 10 then 1 else 0 end) > 0 and
       sum(case when categoryID = 16 then 1 else 0 end) > 0;

子句中的每个条件都在having计算匹配一个类别的行数。您可以轻松地看到这将如何概括更多类别或排除一个类别。例如,如果您想要 10 和 16 而不是 22:

select itemID
from t
group by itemId
having sum(case when categoryID = 10 then 1 else 0 end) > 0 and
       sum(case when categoryID = 16 then 1 else 0 end) > 0 and
       sum(case when categoryID = 22 then 1 else 0 end) = 0;
于 2013-08-27T21:11:44.933 回答
2

将表连接到自身:

select t1.itemID
from mytable t1
join mytable t2 on t2.itemID = t1.itemID
where t1.categoryID = 10
and t2.categoryID = 16;
于 2013-08-27T21:16:15.520 回答