我有一张看起来像这样的表:
-------------------------
| id | areaID | itemID |
-------------------------
| 1 | 7 | 3 |
-------------------------
| 2 | 7 | 4 |
-------------------------
| 3 | 8 | 3 |
-------------------------
| 4 | 10 | 4 |
-------------------------
表示区域7具有项目3和4,区域8仅具有项目3,区域10具有项目4但没有其他项目。
我如何查询同时包含第3项和第4项的areaID?如果是上表,则只返回areaID 7。
答案 0 :(得分:2)
只需要GROUP BY
和HAVING
子句
SELECT areaID
FROM table t
WHERE itemID IN (3,4)
GROUP BY areaID
HAVING COUNT(DISTINCT itemID) = 2
答案 1 :(得分:1)
使用sum来验证每个itemID
的另一种方法应该存在
select areaID
from demo
where itemID in(3,4)
group by areaID
having sum(itemID = 3) >0
and sum(itemID = 4) > 0 ;
或使用exists
select distinct areaid
from demo a
where exists (
select 1
from demo
where itemid = 3 and areaid = a.areaid
) and (
select 1
from demo
where itemid = 4 and areaid = a.areaid
)
答案 2 :(得分:0)
使用分组
{{1}}
答案 3 :(得分:0)
这应该给出结果:areaID = 7
SELECT areaID
FROM table t
WHERE itemId in (3,4)
HAVING COUNT(itemId) > 1