我发现很难解决这个问题所以我会展示我想要做的事情。
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中),我想对得分求和并使该名称在该给定表中唯一。
答案 0 :(得分:3)
以下是使用UNION
和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。
祝你好运。答案 1 :(得分: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
答案 2 :(得分: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带到一行。
答案 3 :(得分: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