MySQL 查詢:針對特定 ID,對來自兩個不同表的相似列的值求和


假設我們有兩個表,這兩個表都有兩列 PlayerId 和 PlayerScore。我們需要將這兩個表中的 PlayerScore 相加,但僅限於特定的 PlayerId。

為此,您可以使用 UNION。讓我們首先建立一個表:

mysql> create table DemoTable1(PlayerId int,PlayerScore int);
Query OK, 0 rows affected (9.84 sec)

使用 insert 命令在表中插入一些記錄:

mysql> insert into DemoTable1 values(1000,87);
Query OK, 1 row affected (3.12 sec)
mysql> insert into DemoTable1 values(1000,65);
Query OK, 1 row affected (1.29 sec)
mysql> insert into DemoTable1 values(1001,10);
Query OK, 1 row affected (1.76 sec)
mysql> insert into DemoTable1 values(1000,45);
Query OK, 1 row affected (2.23 sec)

使用 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);
Query OK, 0 rows affected (11.76 sec)

使用 insert 命令在表中插入一些記錄:

mysql> insert into DemoTable2 values(1000,67);
Query OK, 1 row affected (0.71 sec)
mysql> insert into DemoTable2 values(1001,58);
Query OK, 1 row affected (1.08 sec)
mysql> insert into DemoTable2 values(1000,32);
Query OK, 1 row affected (0.19 sec)

使用 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)

更新於:2019年8月22日

406 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.