2017-09-05 70 views
0

我試圖根據分數和年份來匹配兩張表,以查找哪些id屬於一起。我提出了下面的例子:MySQL按羣組加入

表一:

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

表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具有的得分相同的id = 1對於所有的年,而對於id_match = 20它在年份= 2001年有所不同。我只想匹配所有年份的得分完全相同的ID。

輸出表根本就如下所示:

id | id_match 
1  10 

我想這是一個相對簡單的查詢。我在想是這樣的:

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; 

不過,我想有一場比賽只有ID和id_match的分數等於所有年份。

在此先感謝您的幫助!

回答

0

我想你想:

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

試試這個

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;