如何计算3个不同表中两列的总值?

时间:2015-02-23 23:09:21

标签: mysql add

例如,我有3张桌子; 表1:

+-------+
| count |
+-------+
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
+-------+

表2:

+-------+
| count |
+-------+
|     3 |
|     0 |
|     0 |
|     0 |
|     0 |
+-------+

表3:

+-------+
| count |
+-------+
|     1 |
|     1 |
|     0 |
|     0 |
|     1 |
+-------+

我想计算table1.count + table2.count + table3.count,得到结果,table_right:

+-------+
| count |
+-------+
|     5 |  (1+3+1=5)
|     1 |  (0+0+1=1)
|     0 |  (0+0+0=0)
|     0 |  (0+0+0=0)
|     4 |  (3+0+1=4)
+-------+

但是,如果我使用命令:

 select table1.count+table2.count+table3.count as total
from table1,table2,table3;

结果将变为:

+-------+
| total |
+-------+
|     5 |
|     4 |
|     4 |
|     4 |
|     7 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     5 |
|     4 |
|     4 |
|     4 |
|     7 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     4 |
|     3 |
|     3 |
|     3 |
|     6 |
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
|     4 |
|     3 |
|     3 |
|     3 |
|     6 |
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
|     1 |
|     0 |
|     0 |
|     0 |
|     3 |
|     5 |
|     4 |
|     4 |
|     4 |
|     7 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
|     2 |
|     1 |
|     1 |
|     1 |
|     4 |
+-------+

这不是我想要的结果,如果我尝试

select distinct table1.count+table2.count+table3.count as total
from table1,table2,table3;

我会得到:

+-------+
| total |
+-------+
|     5 |
|     4 |
|     7 |
|     2 |
|     1 |
|     3 |
|     6 |
|     0 |
+-------+

仍然不是我想要的结果。我怎么能得到table_right?

1 个答案:

答案 0 :(得分:2)

如果你添加一个公共id(让我们调用id rowId并假设它在每个表上都有相同的名称),

SELECT t1.count + t2.count + t3.count AS total 
FROM table1 AS t1 
LEFT JOIN table2 AS t2 using (rowId) 
LEFT JOIN table3 AS t3 using (rowId)

如果你没有那些id,我可以考虑所有t1然后所有t2然后所有t3,最后将结果加在一起。

SELECT t1+t2+t3 as total 
FROM (SELECT (SELECT SUM(count) from table1) as t1,
        (SELECT SUM(count) from table2) as t2,
        (SELECT SUM(count) from table3) as t3
    )

查看此SQLFiddle

编辑(2)

添加rowId只需更改表格:

ALTER TABLE table1 ADD COLUMN rowId int not null auto_increment primary key;
ALTER TABLE table2 ADD COLUMN rowId int not null auto_increment primary key;
ALTER TABLE table3 ADD COLUMN rowId int not null auto_increment primary key;