Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

특정 ID에 대해 두 개의 서로 다른 테이블에서 유사한 열의 값을 합산하는 MySQL 쿼리


두 개의 테이블이 있고 두 테이블 모두 PlayerId 및 PlayerScore 열이 있다고 가정해 보겠습니다. 이 두 테이블에서 PlayerScore를 추가해야 하지만 특정 PlayerId에 대해서만 추가해야 합니다.

이를 위해 UNION을 사용할 수 있습니다. 먼저 테이블을 생성하겠습니다 -

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

삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -

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)

삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -

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)