2017-09-05 71 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;