假设我们有两个表,并且两个表都有两列PlayerId和PlayerScore。我们需要从这两个表中添加PlayerScore,但仅针对特定的PlayerId。
为此,您可以使用UNION。让我们首先创建一个表-mysql> create table DemoTable1(PlayerId int,PlayerScore int);
使用插入命令在表中插入一些记录-mysql> insert into DemoTable1 values(1000,87);
mysql> insert into DemoTable1 values(1000,65);
mysql> insert into DemoTable1 values(1001,10);
mysql> insert into DemoTable1 values(1000,45);
使用select语句显示表中的所有记录-mysql> select *from DemoTable1;
这将产生以下输出-+----------+-------------+
| PlayerId | PlayerScore |
+----------+-------------+
| 1000 | 87 |
| 1000 | 65 |
| 1001 | 10 |
| 1000 | 45 |
+----------+-------------+
4 rows in set (0.00 sec)
以下是创建第二个表的查询-mysql> create table DemoTable2(PlayerId int,PlayerScore int);
使用插入命令在表中插入一些记录-mysql> insert into DemoTable2 values(1000,67);
mysql> insert into DemoTable2 values(1001,58);
mysql> insert into DemoTable2 values(1000,32);
使用select语句显示表中的所有记录-mysql> select *from DemoTable2;
这将产生以下输出-+----------+-------------+
| PlayerId | PlayerScore |
+----------+-------------+
| 1000 | 67 |
| 1001 | 58 |
| 1000 | 32 |
+----------+-------------+
3 rows in set (0.00 sec)
以下是对一个表中的一列与另一表中的列求和的查询。在这里,我们为PlayerId 1000添加PlayerScore-mysql> select sum(firstSum) from
(select Sum(PlayerScore) firstSum from DemoTable1 where PlayerId=1000 union
select Sum(PlayerScore) firstSum from DemoTable2 where PlayerId=1000) tbl;
这将产生以下输出-+---------------+
| sum(firstSum) |
+---------------+
| 296 |
+---------------+
1 row in set (0.02 sec)