1-N映射表中的SQL AND和OR

时间:2012-11-27 16:15:13

标签: sql

  

可能重复:
  MySQL select join where AND where

好吧,我有一张桌子 -

 id  map_id     
 -----------
 100   1
 100   2
 101   1
 101   2
 101   3
 102   3

现在,我需要对此数据执行AND和OR运算。也就是说,

OR - 我必须使用map_id 1或3获取所有行的id。因此,如果我查找1或3,则查询应该返回

   100
   102

我可以简单地通过

来做到这一点
  

从表格中选择id,其中map_id为IN(1,3)

AND - 如果我查询1和2,那么我想要ID 100和101.而且,我无法找到查询。

我最初认为像这样的简单查询应该可行,但我错了。

  

从表中选择id,其中map_id = 1 AND map_id = 2 [不起作用]

我想得到这样的结果,但我的查询并没有给我这个。我不想诉诸子查询或加入,好吧,除非我真的不需要。我尝试使用id分组并使用不同的子句但我找到了解决方案。

   100
   101

1 个答案:

答案 0 :(得分:3)

试试这个

select id 
from yourtable
where map_id IN (1,2)
group by id
having COUNT(distinct map_id)=2 -- where this 2 is the number of items you want to find

这种技术称为关系分裂。