MySQL连接两个表并添加列值

时间:2010-05-10 16:00:54

标签: mysql join sum

我对MySQL的了解不是很深入。如果我有两个表,例如这样:

Table1
Date        v1  v2  v3
05/01/2010  26  abc 45
05/02/2010  31  def 25
05/03/2010  50  ghi 46

Table2
Date        v1 v2  v3
05/01/2010  42 jkl 15
05/02/2010  28 mno 14
05/03/2010  12 pqr 64

如何按日期加入查询,并拥有table1.v1和table2.v1的总和,还有table1.v3和table2.v3的总和? V2应该被忽略。

2 个答案:

答案 0 :(得分:6)

您可能需要执行以下操作:

SELECT    t1.date, t1.v1 + t2.v1 AS v1_sum,
          t1.v3 + t2.v3 AS v3_sum
FROM      table1 t1
JOIN      table2 t2 ON (t1.date = t2.date);

如果您想要两列的总聚合,您还可以执行以下操作:

SELECT    SUM(t1.v1 + t2.v1) AS v1_sum,
          SUM(t1.v3 + t2.v3) AS v3_sum
FROM      table1 t1
JOIN      table2 t2 ON (t1.date = t2.date);

测试用例:

CREATE TABLE table1 (`date` date, `v1` int, `v3` int);
CREATE TABLE table2 (`date` date, `v1` int, `v3` int);

INSERT INTO table1 VALUES ('2010-05-01', 26, 45);
INSERT INTO table1 VALUES ('2010-05-02', 31, 25);
INSERT INTO table1 VALUES ('2010-05-03', 50, 46);

INSERT INTO table2 VALUES ('2010-05-01', 42, 15);
INSERT INTO table2 VALUES ('2010-05-02', 28, 14);
INSERT INTO table2 VALUES ('2010-05-03', 12, 64);

首先查询结果:

+------------+--------+--------+
| date       | v1_sum | v3_sum |
+------------+--------+--------+
| 2010-05-01 |     68 |     60 |
| 2010-05-02 |     59 |     39 |
| 2010-05-03 |     62 |    110 |
+------------+--------+--------+

第二个查询结果:

+--------+--------+
| v1_sum | v3_sum |
+--------+--------+
|    189 |    209 |
+--------+--------+

答案 1 :(得分:0)

创建表格corse ( id int(11), cname varchar(10),
cdet varchar(10) );

然后创建另一个表

创建表格 ( id int(11),
sname varchar(10),
ssub varchar(10)
);

然后在表格

上添加主键

alter table stud add主键(id);

然后在corse上应用外键

alter table corse添加外键(id)引用stud(id);

这是它的最后和最后一步

从stud s join corse c o中选择s.id,s.sname,c.cname,c.cdet n s.id = c.id;