要获得MySQL结果的最后一行的总数,请使用以下语法-
( SELECT yourColumnName1, yourColumnName2, yourColumnName3, . . N FROM yourTableName ) UNION ( SELECT "yourMessage" AS anyAliasName1, SUM(yourColumnName1) AS anyAliasName2, SUM(yourColumnName2) AS anyAliasName3, . . N FROM yourTableName );
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table ProductDemo -> ( -> ProductId varchar(10), -> ProductQuantity int, -> ProductValue int -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into ProductDemo values('Product-1',10,300); mysql> insert into ProductDemo values('Product-2',5,200); mysql> insert into ProductDemo values('Product-3',7,340); mysql> insert into ProductDemo values('Product-4',20,500); mysql> insert into ProductDemo values('Product-5',30,1000);
使用select语句显示表中的所有记录。查询如下-
mysql> select *from ProductDemo;
以下是输出-
+-----------+-----------------+--------------+ | ProductId | ProductQuantity | ProductValue | +-----------+-----------------+--------------+ | Product-1 | 10 | 300 | | Product-2 | 5 | 200 | | Product-3 | 7 | 340 | | Product-4 | 20 | 500 | | Product-5 | 30 | 1000 | +-----------+-----------------+--------------+ 5 rows in set (0.00 sec)
这是在MySQL结果的最后一行中获取总计的查询-
mysql> (SELECT ProductId, -> ProductQuantity, -> ProductValue -> FROM ProductDemo) -> UNION -> (SELECT "Total" AS ProductName, -> SUM(ProductQuantity) AS TotalQuantity, -> SUM(ProductValue) AS TotalValue -> FROM ProductDemo);
输出结果
+-----------+-----------------+--------------+ | ProductId | ProductQuantity | ProductValue | +-----------+-----------------+--------------+ | Product-1 | 10 | 300 | | Product-2 | 5 | 200 | | Product-3 | 7 | 340 | | Product-4 | 20 | 500 | | Product-5 | 30 | 1000 | | Total | 72 | 2340 | +-----------+-----------------+--------------+ 6 rows in set (0.00 sec)