2010-12-22 79 views
0

我使用VB.Net表达与Access文件,我有如下表:SQL查询与多对多表

table Formula 
id | name 
------------------- 
1 | formula 1 
2 | formula 2 
3 | formula 3 


table Component 
id | name 
-------------------- 
1 | A 
2 | B 
3 | C 
4 | D 


table FormulaComponents 
formula_id | component_id 
------------------------- 
1 | 1 
1 | 2 
1 | 4 
2 | 1 
2 | 3 
2 | 4 
3 | 1 
3 | 2 
3 | 3 

因此,每个配方都有一个或多个组件。

如果我想使用例如组件A和组件D(结果:公式1,公式2)的所有公式,我将使用哪个查询?我试着用十字交叉的东西,但它似乎不能在VB中工作...

谢谢!

+1

你想都只有A和d或公式,可能有其他的项目呢? – 2010-12-22 15:05:09

+0

其他项目也是如此。 – 2010-12-22 15:31:34

回答

0
SELECT DISTINCT 
    f.* 
FROM Formula f 
INNER JOIN FormulaComponent fc on fc.formula_id = f.formula_id 
INNER JOIN Component c on c.component_id = fc.componentid 
WHERE Exists (SELECT * FROM FormulaComponent fc1 WHERE fc1.formulaID = f.formulaId AND c.Name = 'A') 
    AND Exists (SELECT * FROM FormulaComponent fc1 WHERE fc1.formulaID = f.formulaId AND c.Name = 'D') 
2

更新:

select f.* 
from (
    select c.id 
    from FormulaComponents fc 
    inner join Component c on fc.component_id = c.id 
    where c.name in ('A', 'B') 
    group by c.id 
    having count(distinct c.name) = 2 
) c2 
inner join FormulaComponents fc on c2.id = fc.component_id 
inner join Formula f on fc.formula_id = f.id