2014-09-25 65 views
1

我有表A和B有关系:A < - > 1B关系。SQL选择不同的地方在其他表中存在每个id的行

他们加入了AB区域= B.id,其中B.id是唯一

我有一个参数,即B.

的ID的一堆

我想不同的A.id有全部给B.ids分配。

实施例:

表B

| id | ... 
| 1 | 
| 2 | 
| 3 | 

表A

| id | b | ... 
| 1 | 1 | 
| 1 | 2 | 
| 1 | 3 | 
| 2 | 1 | 
| 2 | 2 | 
       <-- id=2 is not assigned to b=3 ! 
| 3 | 1 | 
| 3 | 2 | 
| 3 | 3 | 

预期用于parame结果ter B.ids =“1,2,3”:1,3(2错过所需的B.id = 3)

我该怎么做?

回答

4

您可以聚集和having条款做到这一点:

select id 
from tableA a join 
    tableB b 
    on a.b = b.id 
group by id 
having count(distinct b) = (select count(distinct b) from tableB); 

注意它可能会进行一些假设来简化。举例来说,如果你知道b ID是唯一的,那么你就不需要count(distinct)count()就足以。)

编辑:

如果你想,你要检查ID的列表,你可以使用:

select id 
from tableA a 
where find_in_set(a.b, IDLISTHERE) > 0 
group by id 
having count(distinct b) = (select count(distinct b) from tableB where find_in_set(a.b, IDLISTHERE) > 0); 
+0

是b.id是唯一 – Stuck 2014-09-25 12:03:56

+0

看起来不错,但如果是参数? – Stuck 2014-09-25 12:05:14

+0

为参数=“1,2,3”:也许加:“有count(b)=:param_size 其中b.id IN(:param)” – Stuck 2014-09-25 12:17:10

0
select id from tableA a join tableB b on a.b = b.id 
group by id 
having count(distinct b) = (select count(distinct b) from tableB); 
+0

这是什么戈登Linoff已发布,但参数在哪里?我只希望来自表A的那些分配给参数定义的Bs的选择。 – Stuck 2014-09-25 12:10:21

相关问题