MySQL查询从具有相似列“ UP”的5张表中计算总和?
为此,请将UNION ALL与一起使用SUM()
。让我们创建5个表-
mysql> create table DemoTable1977(
UP int
);
mysql> insert into DemoTable1977 values(10);
mysql> insert into DemoTable1977 values(20);
mysql> select * from DemoTable1977;
+------+
| UP |
+------+
| 10 |
| 20 |
+------+
2 rows in set (0.00 sec)
mysql> create table DemoTable1978
(
UP int
);
mysql> insert into DemoTable1978 values(30);
mysql> select * from DemoTable1978;
+------+
| UP |
+------+
| 30 |
+------+
1 row in set (0.00 sec)
mysql> create table DemoTable1979
(
UP int
);
mysql> insert into DemoTable1979 values(40);
mysql> select * from DemoTable1979;
+------+
| UP |
+------+
| 40 |
+------+
1 row in set (0.00 sec)
mysql> create table DemoTable1980
(
UP int
);
mysql> insert into DemoTable1980 values(50);
mysql> select * from DemoTable1980;
+------+
| UP |
+------+
| 50 |
+------+
1 row in set (0.00 sec)
mysql> create table DemoTable1981
(
UP int
);
mysql> insert into DemoTable1981 values(60);
mysql> select * from DemoTable1981;
+------+
| UP |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
这是一个查询,用于从5个表中计算总和,其中一个列名为“ UP”-
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)
以上是 MySQL查询从具有相似列“ UP”的5张表中计算总和? 的全部内容, 来源链接: utcz.com/z/321953.html