使用MySQL在表的最后一行显示总和?

要在表的最后一行显示总和,可以使用UNION。要了解如何操作,让我们创建一个表

mysql> create table showSumInLastRowDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> StudentMarks int
   -> );

使用insert命令在表中插入一些记录。查询如下-

mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('John',56);
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('John',87);
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('John',52);
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('Carol',97);
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('Larry',75);
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('Larry',98);
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('Carol',73);

使用select语句显示表中的所有记录。查询如下-

mysql> select *from showSumInLastRowDemo;

以下是输出

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|         1 | John        |           56 |
|         2 | John        |           87 |
|         3 | John        |           52 |
|         4 | Carol       |           97 |
|         5 | Larry       |           75 |
|         6 | Larry       |           98 |
|         7 | Carol       |           73 |
+-----------+-------------+--------------+
7 rows in set (0.00 sec)

这是使用MySQL在表的最后一行显示总和的查询

mysql> (select StudentName,StudentMarks from showSumInLastRowDemo)
   -> UNION
   -> (select 'TotalMarksOfAllStudent' as StudentName,sum(StudentMarks) StudentMarks from showSumInLastRowDemo);

以下是输出

+------------------------+--------------+
| StudentName            | StudentMarks |
+------------------------+--------------+
| John                   |           56 |
| John                   |           87 |
| John                   |           52 |
| Carol                  |           97 |
| Larry                  |           75 |
| Larry                  |           98 |
| Carol                  |           73 |
| TotalMarksOfAllStudent |          538 |
+------------------------+--------------+
8 rows in set (0.00 sec)