3

我发现很难提出这个问题,所以我将展示我正在尝试做的事情。

Table1 (ID, Name, Score)  
1 Jane  10  
2 Jack  15  
3 Jill  12  
4 Jane  10  


Table2 (ID, Name, Score)  
1 John  11  
2 Jill  14  
3 Jack  16  
4 Jake  15  

我想要的结果是

Result (Name, Table1.Score, Table2.Score)  
Jane 20   NULL
Jack 15   16
Jill 12   14
John NULL 11
Jake NULL 15

名称可以成为主键吗?请注意,Jane 在表 1 中出现了两次(也可能出现在表 2 中),我想对分数求和并使名称在给定表中唯一。

4

4 回答 4

3

这是使用UNIONand的一种方法SUM

SELECT T.Name, Sum(T.Score), Sum(T2.Score) Score2
FROM (SELECT Name, SUM(Score) score FROM Table1 GROUP BY Name)  t
  LEFT JOIN (SELECT Name, SUM(Score) score FROM Table2  GROUP BY Name) t2
ON t.Name = t2.Name
GROUP BY T.Name
UNION   
SELECT T.Name, Sum(T2.Score), Sum(T.Score) Score2
FROM (SELECT Name, SUM(Score) score FROM Table2 GROUP BY Name)  t
  LEFT JOIN (SELECT Name, SUM(Score) score FROM Table1  GROUP BY Name) t2
ON t.Name = t2.Name
GROUP BY T.Name

这是SQL Fiddle

祝你好运。

于 2013-02-11T17:09:26.013 回答
2

尝试这个

 select  t1.name , sum(t1.score) as score1 ,sum(t2.score2) as score2 from Table1 as t1
 left JOIN 
 (select  name , score as score2 from Table2 )t2 
 on t1.name = t2.name 
 group by name

 union all

 select  t2.name , sum(t1.score1) as score1, sum(t2.score) as score2  from Table2 as t2
 left JOIN 
 (select  name , score as score1 from Table1 )t1 
 on t2.name = t1.name 
 where score1 is  null

 group by name
 ---- if you want use the order add this "order by name" here in the end

这将输出:

  NAME |    SCORE1  |SCORE2
  Jack |     15     | 16
  Jane |     20     |(null)
  Jill |     12     | 14
  Jake |    (null)  | 15
  John |    (null)  | 11

这里 SQLFIDDLE 演示

于 2013-02-11T18:15:43.810 回答
1

好吧,如果 MySQL 有full outer join,你会使用它。这是另一种方法:

select id, name, MAX(score1) as score1, MAX(score2) as score2
from ((select  id, name, score as score1, NULL as score2
       from table1
      ) union all
      (select  id, name, null as score1, score as score2
       from table1
      )
     ) t
group by id, name

这个想法是从每个表中获取所有需要的信息,分数在不同的列中,通过使用union all并将分数分成两个单独的列。

决赛group by将他们聚集在一起,每个 id 一行。

于 2013-02-11T17:09:29.090 回答
0

尝试这个:

select 
name = Table1.name, 
sum(Table1.score) as score1,
sum(Table2.Score) as score2
from Table1
full outer join
Table2 
ON 
Table2.name = Table1.name
where Table1.name is not null
group by table1.name

UNION

select 
name = Table2.name, 
sum(Table1.score) as score1,
sum(Table2.Score) as score2
from Table1
full outer join
Table2 
ON 
Table2.name = Table1.name
where Table2.name is not null
group by table2.name

order by score1 desc, score2
于 2013-02-11T21:49:42.657 回答