我有3个表如何加入它们来生成一个表?

时间:2010-10-18 01:05:59

标签: mysql

表a(作者表)

author_id
author_name

表b(表格后)

post_id
author_id

表c(收益表)

post_id (post id is not unique)
post_earning

我想生成一份包含每位作者收入的报告。

author_id
author_name
total_earning (sum of earnings of all the posts by author)

使用的SQL查询:

SELECT
   a.author_id,
   a.author_name,
   sum(post_earnings) as total_earnings
FROM TableA a
Inner Join TableB b on b.author_id = a.author_id
Inner Join TableC c on c.post_id = b.post_id
Group By 
   a.author_id,
   a.author_name

我得到的结果是:

ID  user_login  total_earnings
2   Redstar 13.99
7   Redleaf 980.18
10  topnhotnews 80.43
11  zmmishad    39.27
13  rashel  1248.34
14  coolsaint   1.66
16  hotnazmul   9.83
17  rubel   0.14
21  mahfuz1986  1.09
48  ripon   12.96
60  KHK 27.81

总收入的总和实际上是2863.22。但如果我添加结果表的所有值,我得到2415.问题出在哪里?使用的样本表可以从第一条评论中的链接下载。

2 个答案:

答案 0 :(得分:3)

SELECT
   a.author_id,
   a.author_name,
   sum(post_earnings) as total_earnings
FROM TableA a
Inner Join TableB b on b.author_id = a.author_id
Inner Join TableC c on c.post_id = b.post_id
Group By 
   a.author_id,
   a.author_name

答案 1 :(得分:1)

您确定表格中有正确的数据吗?也许TableA中缺少作者或帖子表中的某些帖子。