2017-09-05 3 views
0

Ich versuche zwei Tabellen basierend auf Score und Jahr zu finden, um herauszufinden, welche IDs zusammen gehören. Ich habe das folgende Beispiel folgenden:MySQL Join by groups

Tabelle a:

id | score | year 
    1  0  2000 
    1  1  2001 
    1  2  2002 

Tabelle b:

id_match | score_match | year 
    10   0   2000 
    10   1   2001 
    10   2   2002 
    20   0   2000 
    20   0   2001 
    20   2   2002 

id_match = 10 hat die gleichen Werte wie id = 1for das ganze Jahr, während für id_match = 20 es ist anders in Jahr = 2001. Ich möchte nur die IDs übereinstimmen, die in allen Jahren genau die gleiche Punktzahl haben.

Die Ausgabetabelle aussehen könnte einfach wie folgt:

id | id_match 
1  10 

Ich denke, es ist eine relativ einfache Abfrage. Ich dachte an so etwas wie dieses:

SELECT a.id, b.id_match 
FROM a 
LEFT JOIN b 
    ON a.score = b.score 
    AND a.year = b.year 
GROUP BY a.id, b.id_match; 

Aber ich möchte ein Spiel haben, nur dann, wenn Noten von id und id_match für alle Jahre gleich sind.

Vielen Dank im Voraus für Hilfe!

Antwort

0

Ich glaube, Sie wollen:

SELECT b.id_match 
FROM a JOIN 
    b 
    ON a.year = b.year 
GROUP BY b.id_match 
HAVING SUM(a.score <> b.score_match) = 0; 
0

Versuchen Sie dieses

select a.id, b.id_match from tableA a, tableB b 
    where a.score = b.score 
    and a.year = b.year 
    and b.id_match not in (select b.id_match from tableB b, tableA a 
          where b.score != a.score 
           and b.year = a.year 
          group by b.id_match) 
group by a.id, b.id_match;