如何在 MySQL 中正确使用 WITH ROLLUP?
mysqlmysqli database
使用 WITH ROLLUP 的语法如下 −
select yourColumnName1,sum(yourColumnName2) from yourTableName group by yourColumnName1 with rollup;
首先我们创建一个表 −
mysql> create table DemoTable1622 -> ( -> EmployeeCountryName varchar(20), -> EmployeeSalary int -> ); Query OK, 0 rows affected (0.44 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1622 values('US',4500); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1622 values('UK',1500); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1622 values('AUS',1700); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1622 values('UK',1900); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1622 values('US',3900); Query OK, 1 row affected (0.42 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1622;
这将产生以下输出 −
+---------------------+----------------+ | EmployeeCountryName | EmployeeSalary | +---------------------+----------------+ | US | 4500 | | UK | 1500 | | AUS | 1700 | | UK | 1900 | | US | 3900 | +---------------------+----------------+ 5 rows in set (0.00 sec)
这是在 MySQL 中正确使用 WITH ROLLUP 的查询 −
mysql> select EmployeeCountryName,sum(EmployeeSalary) from DemoTable1622 -> group by EmployeeCountryName with rollup;
这将产生以下输出 −
+---------------------+---------------------+ | EmployeeCountryName | sum(EmployeeSalary) | +---------------------+---------------------+ | AUS | 1700 | | UK | 3400 | | US | 8400 | | NULL | 13500 | +---------------------+---------------------+ 4 rows in set (0.02 sec)