具有多对多表的SQL查询

时间:2010-12-22 14:57:57

标签: sql vb.net ms-access

我正在使用带有Access文件的VB.Net express,我有以下表格:

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中不起作用...

谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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')