2010-12-22 19 views
0

Ich verwende VB.Net mit einer Access-Datei ausdrücken, und ich habe die folgenden Tabellen:SQL-Abfrage mit vielen zu vielen Tabellen

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 

So jede Formel eine oder mehr Komponenten.

Welche Abfrage verwende ich, wenn ich alle Formeln mit zB Komponente A UND Komponente D (Ergebnis: Formel 1, Formel 2) möchte? Ich versuche etwas mit Schnittpunkt, aber es scheint, es funktioniert nicht in VB ...

Vielen Dank!

+1

Haben Sie die Formeln alle mit ONLY A und D wollen oder dass auch andere Elemente wie gut? –

+0

Andere Gegenstände auch. –

Antwort

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

Update:

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 
+0

+1 Kluge Verwendung des Habens und zählen (distinct [Spalte]) .... Ich mag es. –

+0

.. Sehen Sie, was Sie für diese Frage http://stackoverflow.com/questions/4510185/select-max-value-of-each-group/4510200#4510200 kommen können. Ich glaube nicht, dass ich ihm wirklich geholfen habe. –

+0

Danke, aber diese Abfrage gibt Komponenten zurück, ich brauche die Formeln, in denen die Komponenten sind ... –

Verwandte Themen