2014-09-25 67 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

相關問題