问题描述
我有一个数据库...
descriptionID | ItemID | description
--------------------------------------------
1 | 1 | Blue
2 | 1 | Small
3 | 1 | Circular
4 | 2 | Blue
5 | 2 | Large
6 | 3 | Small
7 | 4 | Blue
... ... ...
我想返回itemID,其中有蓝色且很小的条目,因此返回itemID = 1,没有其他itemID。
ItemID
--------------
1
解决方法
您可以使用聚合。假设没有重复:
select itemid
from t
where description in ('Blue','Small')
group by itemid
having count(*) = 2;
,
按照您的要求写出来。
描述为Blue
的项目和(设置相交)描述为Small
的项目
select itemId from tab where description = 'Blue'
INTERSECT
select itemId from tab where description = 'Small';
,
您可以使用以下内容:
SELECT DISTINCT itemId FROM tbl t1
WHERE EXISTS (SELECT * FROM tbl WHERE description = 'Blue' AND itemId = t1.itemId)
AND EXISTS (SELECT * FROM tbl WHERE description = 'Small' AND itemId = t1.ItemId)