MySQL में UNION से दो टेबल के कॉलम का योग करना
दो टेबल में समान कॉलम (PlayerId, PlayerScore) हैं। किसी विशेष PlayerId के लिए दोनों टेबल के PlayerScore का योग निकालने के लिए 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)
दूसरी टेबल बनाना और डेटा डालना
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)
PlayerId 1000 के लिए दोनों टेबल का योग
mysql> SELECT SUM(firstSum) FROM (
SELECT SUM(PlayerScore) AS firstSum FROM DemoTable1 WHERE PlayerId = 1000
UNION
SELECT SUM(PlayerScore) AS firstSum FROM DemoTable2 WHERE PlayerId = 1000
) AS tbl;
परिणाम
+---------------+ | SUM(firstSum) | +---------------+ | 296 | +---------------+ 1 row in set (0.02 sec)
व्याख्या: प्रत्येक टेबल से PlayerId 1000 का योग अलग-अलग निकाला जाता है, फिर UNION से मिलाया जाता है, और अंत में बाहरी SUM() से कुल योग मिलता है। (87+65+45) + (67+32) = 197 + 99 = 296।