【问题标题】:Sql query with many to many tables具有多对多表的 Sql 查询
【发布时间】:2010-12-22 14:57:57
【问题描述】:

我正在使用带有 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 中不起作用......

谢谢!

【问题讨论】:

  • 您想要所有只有 A 和 D 的公式还是可能还有其他项目?

标签: sql vb.net ms-access


【解决方案1】:

更新:

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

【讨论】:

  • .. 看看你能想出什么来回答这个问题stackoverflow.com/questions/4510185/…。因为我不认为我真的帮助了他。
  • 谢谢,但是这个查询返回组件,我需要组件所在的公式...
【解决方案2】:
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')

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多