Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL: คำนวณผลรวมจาก 5 ตารางที่มีคอลัมน์ชื่อ "UP" เหมือนกัน

สร้างตารางตัวอย่าง 5 ตาราง

สร้างตาราง DemoTable1977 ถึง DemoTable1981 ทุกตารางมีโครงสร้างเดียวกัน คือ คอลัมน์ UP แบบ integer:

mysql> create table DemoTable1977 ( UP int ); Query OK, 0 rows affected (0.00 sec)
mysql> insert into DemoTable1977 values(10); ...
mysql> create table DemoTable1978 ( UP int ); ...
mysql> create table DemoTable1979 ( UP int ); ...
mysql> create table DemoTable1980 ( UP int ); ...
mysql> create table DemoTable1981 ( UP int ); ...

ข้อมูลในแต่ละตาราง

  • DemoTable1977: 10, 20 (รวม 30)
  • DemoTable1978: 30 (รวม 30)
  • DemoTable1979: 40 (รวม 40)
  • DemoTable1980: 50 (รวม 50)
  • DemoTable1981: 60 (รวม 60)

Query คำนวณผลรวมทั้งหมด

ใช้ UNION ALL รวมผลรวมของแต่ละตาราง แล้วค่อย SUM() ทั้งหมด:

mysql> select sum(TotalSum) from ( select sum(UP) as TotalSum from DemoTable1977 union all select sum(UP) from DemoTable1978 union all select sum(UP) from DemoTable1979 union all select sum(UP) from DemoTable1980 union all select sum(UP) from DemoTable1981 ) tbl;

ผลลัพธ์

+---------------+
| sum(TotalSum) |
+---------------+
|           210 |
+---------------+
1 row in set (0.00 sec)

การคำนวณ: 30 + 30 + 40 + 50 + 60 = 210

หมายเหตุ

  • UNION ALL เร็วกว่า UNION เพราะไม่ลบแถวซ้ำ (ซึ่งในที่นี้ไม่มีโอกาสซ้ำเพราะเป็นผลรวมของตารางต่างกัน)
  • หากตารางเยอะมาก ควรพิจารณาใช้ View หรือ Stored Procedure เพื่อความสะดวกในการบำรุงรักษา