- MySQL 基础
- MySQL - 首页
- MySQL - 简介
- MySQL - 特性
- MySQL - 版本
- MySQL - 变量
- MySQL - 安装
- MySQL - 管理
- MySQL - PHP 语法
- MySQL - Node.js 语法
- MySQL - Java 语法
- MySQL - Python 语法
- MySQL - 连接
- MySQL - Workbench
- MySQL 数据库
- MySQL - 创建数据库
- MySQL - 删除数据库
- MySQL - 选择数据库
- MySQL - 显示数据库
- MySQL - 复制数据库
- MySQL - 数据库导出
- MySQL - 数据库导入
- MySQL - 数据库信息
- MySQL 用户
- MySQL - 创建用户
- MySQL - 删除用户
- MySQL - 显示用户
- MySQL - 修改密码
- MySQL - 授予权限
- MySQL - 显示权限
- MySQL - 收回权限
- MySQL - 锁定用户帐户
- MySQL - 解锁用户帐户
- MySQL 表
- MySQL - 创建表
- MySQL - 显示表
- MySQL - 修改表
- MySQL - 重命名表
- MySQL - 克隆表
- MySQL - 清空表
- MySQL - 临时表
- MySQL - 修复表
- MySQL - 描述表
- MySQL - 添加/删除列
- MySQL - 显示列
- MySQL - 重命名列
- MySQL - 表锁定
- MySQL - 删除表
- MySQL - 派生表
- MySQL 查询
- MySQL - 查询
- MySQL - 约束
- MySQL - INSERT 查询
- MySQL - SELECT 查询
- MySQL - UPDATE 查询
- MySQL - DELETE 查询
- MySQL - REPLACE 查询
- MySQL - INSERT IGNORE
- MySQL - INSERT ON DUPLICATE KEY UPDATE
- MySQL - INSERT INTO SELECT
- MySQL 运算符和子句
- MySQL - WHERE 子句
- MySQL - LIMIT 子句
- MySQL - DISTINCT 子句
- MySQL - ORDER BY 子句
- MySQL - GROUP BY 子句
- MySQL - HAVING 子句
- MySQL - AND 运算符
- MySQL - OR 运算符
- MySQL - LIKE 运算符
- MySQL - IN 运算符
- MySQL - ANY 运算符
- MySQL - EXISTS 运算符
- MySQL - NOT 运算符
- MySQL - NOT EQUAL 运算符
- MySQL - IS NULL 运算符
- MySQL - IS NOT NULL 运算符
- MySQL - BETWEEN 运算符
- MySQL - UNION 运算符
- MySQL - UNION vs UNION ALL
- MySQL - MINUS 运算符
- MySQL - INTERSECT 运算符
- MySQL - INTERVAL 运算符
- MySQL 连接
- MySQL - 使用连接
- MySQL - INNER JOIN
- MySQL - LEFT JOIN
- MySQL - RIGHT JOIN
- MySQL - CROSS JOIN
- MySQL - FULL JOIN
- MySQL - 自连接
- MySQL - DELETE JOIN
- MySQL - UPDATE JOIN
- MySQL - UNION vs JOIN
- MySQL 触发器
- MySQL - 触发器
- MySQL - 创建触发器
- MySQL - 显示触发器
- MySQL - 删除触发器
- MySQL - BEFORE INSERT 触发器
- MySQL - AFTER INSERT 触发器
- MySQL - BEFORE UPDATE 触发器
- MySQL - AFTER UPDATE 触发器
- MySQL - BEFORE DELETE 触发器
- MySQL - AFTER DELETE 触发器
- MySQL 数据类型
- MySQL - 数据类型
- MySQL - VARCHAR
- MySQL - BOOLEAN
- MySQL - ENUM
- MySQL - DECIMAL
- MySQL - INT
- MySQL - FLOAT
- MySQL - BIT
- MySQL - TINYINT
- MySQL - BLOB
- MySQL - SET
- MySQL 正则表达式
- MySQL - 正则表达式
- MySQL - RLIKE 运算符
- MySQL - NOT LIKE 运算符
- MySQL - NOT REGEXP 运算符
- MySQL - regexp_instr() 函数
- MySQL - regexp_like() 函数
- MySQL - regexp_replace() 函数
- MySQL - regexp_substr() 函数
- MySQL 函数和运算符
- MySQL - 日期和时间函数
- MySQL - 算术运算符
- MySQL - 数值函数
- MySQL - 字符串函数
- MySQL - 聚合函数
- MySQL 其他概念
- MySQL - NULL 值
- MySQL - 事务
- MySQL - 使用序列
- MySQL - 处理重复项
- MySQL - SQL 注入
- MySQL - 子查询
- MySQL - 注释
- MySQL - 检查约束
- MySQL - 存储引擎
- MySQL - 将表导出到 CSV 文件
- MySQL - 将 CSV 文件导入数据库
- MySQL - UUID
- MySQL - 通用表表达式
- MySQL - ON DELETE CASCADE
- MySQL - Upsert
- MySQL - 水平分区
- MySQL - 垂直分区
- MySQL - 游标
- MySQL - 存储函数
- MySQL - SIGNAL
- MySQL - RESIGNAL
- MySQL - 字符集
- MySQL - 排序规则
- MySQL - 通配符
- MySQL - 别名
- MySQL - ROLLUP
- MySQL - 今日日期
- MySQL - 字面量
- MySQL - 存储过程
- MySQL - EXPLAIN
- MySQL - JSON
- MySQL - 标准差
- MySQL - 查找重复记录
- MySQL - 删除重复记录
- MySQL - 选择随机记录
- MySQL - SHOW PROCESSLIST
- MySQL - 更改列类型
- MySQL - 重置自动递增
- MySQL - COALESCE() 函数
- MySQL 有用资源
- MySQL - 有用函数
- MySQL - 语句参考
- MySQL - 快速指南
- MySQL - 有用资源
- MySQL - 讨论
MySQL - ROLLUP
MySQL ROLLUP 子句
MySQL ROLLUP 子句是 GROUP BY 子句的扩展。它与 MySQL 中的聚合函数一起使用,用于在表中额外的一行中查找列值的总计或汇总(也称为列的超级聚合)。
考虑一个制造工厂,它在一个表中跟踪每月的生产数据。为了确定年度产品产量,您可以使用 SUM() 聚合函数和 ROLLUP。但是,如果您需要找出生产低于特定阈值的月份数量,ROLLUP 将允许您使用 COUNT() 函数计算这些月份。
语法
以下是 MySQL 中 ROLLUP 子句的语法:
SELECT AggregateFunction(column_name(s)), column_name(s) FROM table_name GROUP BY column_name(s) WITH ROLLUP;
示例
首先,我们将创建一个名为“PRODUCT”的表,其中包含生产信息,例如产品 ID、产品名称、产品数量和组织内的生产月份:
CREATE TABLE PRODUCT ( PRODUCT_ID INT, PRODUCT_NAME VARCHAR(50), PRODUCT_COUNT INT, MONTH VARCHAR(20) );
现在,让我们将一些数据插入到上面创建的表中:
INSERT INTO PRODUCT VALUES (101, 'Comb', 2345, 'January'), (102, 'Coffee Mugs', 1242, 'January'), (103, 'Cutlery', 124, 'January'), (101, 'Comb', 3263, 'February'), (102, 'Coffee Mugs', 10982, 'February'), (103, 'Cutlery', 435, 'February');
获得的 PRODUCT 表如下:
PRODUCT_ID | PRODUCT_NAME | PRODUCT_COUNT | MONTH |
---|---|---|---|
101 | 梳子 | 2345 | 一月 |
102 | 咖啡杯 | 1242 | 一月 |
103 | 餐具 | 124 | 一月 |
101 | 梳子 | 3263 | 二月 |
102 | 咖啡杯 | 10982 | 二月 |
103 | 餐具 | 435 | 二月 |
现在,让我们使用 ROLLUP 查找每个月份生产的产品总和,如下所示:
SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP;
输出
您可以在下面的输出中观察到,计算了一月和二月的单个产品数量,并且使用 ROLLUP 在第三行显示了总生产量的总计:
SUM(PRODUCT_COUNT) | MONTH |
---|---|
14680 | 二月 |
3711 | 一月 |
18391 | NULL |
多列 ROLLUP
您还可以通过使用 GROUP BY 子句将它们组合在一起,在多个列上使用 ROLLUP。
示例
在这里,我们将 GROUP BY 子句应用于 PRODUCT 表的 'PRODUCT_ID' 和 'PRODUCT_NAME' 列:
SELECT PRODUCT_ID, COUNT(PRODUCT_ID) AS PROD_ID_COUNT, PRODUCT_NAME, COUNT(PRODUCT_NAME) AS PROD_ID_NAME FROM PRODUCT GROUP BY PRODUCT_ID, PRODUCT_NAME;
我们得到以下输出:
PRODUCT_ID | PROD_ID_COUNT | PRODUCT_NAME | PROD_ID_NAME |
---|---|---|---|
101 | 2 | 梳子 | 2 |
102 | 2 | 咖啡杯 | 2 |
103 | 2 | 餐具 | 2 |
现在,让我们使用 ROLLUP 计算这两行的摘要,如下面的查询所示:
SELECT PRODUCT_ID, COUNT(PRODUCT_ID) AS PROD_ID_COUNT, PRODUCT_NAME, COUNT(PRODUCT_NAME) AS PROD_ID_NAME FROM PRODUCT GROUP BY PRODUCT_ID, PRODUCT_NAME WITH ROLLUP;
您可以在下面的输出中看到,不仅在最终级别计算了摘要,而且还在两个级别上计算了摘要。为每个产品名称显示一个列摘要:
PRODUCT_ID | PROD_ID_COUNT | PRODUCT_NAME | PROD_ID_NAME |
---|---|---|---|
101 | 2 | 梳子 | 2 |
101 | 2 | NULL | 2 |
102 | 2 | 咖啡杯 | 2 |
102 | 2 | NULL | 2 |
103 | 2 | 餐具 | 2 |
103 | 2 | NULL | 2 |
NULL | 6 | NULL | 6 |
使用客户端程序进行 Rollup
我们也可以使用客户端程序执行 rollup。
语法
要通过 PHP 程序使用带有聚合函数的 ROLLUP 计算列的总计,我们需要使用mysqli 函数query()执行“SELECT”语句,如下所示:
$sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; $mysqli->query($sql);
要通过 JavaScript 程序使用带有聚合函数的 ROLLUP 计算列的总计,我们需要使用mysql2 库的query() 函数执行“SELECT”语句,如下所示:
sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; con.query(sql);
要通过 Java 程序使用带有聚合函数的 ROLLUP 计算列的总计,我们需要使用JDBC 函数executeQuery()执行“SELECT”语句,如下所示:
String sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; statement.executeQuery(sql);
要通过 Python 程序使用带有聚合函数的 ROLLUP 计算列的总计,我们需要使用MySQL Connector/Python 的execute() 函数执行“SELECT”语句,如下所示:
rollup_query = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP" cursorObj.execute(rollup_query)
示例
以下是程序:
$dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $db = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $sql = "CREATE TABLE PRODUCT ( PRODUCT_ID INT, PRODUCT_NAME VARCHAR(50), PRODUCT_COUNT INT, MONTH VARCHAR(20) )"; if($mysqli->query($sql)){ printf("Product table created successfully....!"); } //now let's insert some records into the table $sql = "INSERT INTO PRODUCT VALUES(101, 'Comb', 2345, 'January')"; if($mysqli->query($sql)){ printf("First record inserted successfully...!\n"); } $sql = "INSERT INTO PRODUCT VALUES(102, 'Coffee Mugs', 1242, 'January')"; if($mysqli->query($sql)){ printf("Second record inserted successfully...!\n"); } $sql = "INSERT INTO PRODUCT VALUES(103, 'Cutlery', 124, 'January')"; if($mysqli->query($sql)){ printf("Third record inserted successfully...!\n"); } $sql = "INSERT INTO PRODUCT VALUES(101, 'Comb', 3263, 'February')"; if($mysqli->query($sql)){ printf("Fourth record inserted successfully...!\n"); } //display the table records $sql = "SELECT * FROM PRODUCT"; if($result = $mysqli->query($sql)){ printf("Table records: \n"); while($row = mysqli_fetch_array($result)){ printf("PRODUCT_ID: %d, PRODUCT_NAME: %s, PRODUCT_COUNT: %d, MONTH: %s", $row['PRODUCT_ID'], $row['PRODUCT_NAME'], $row['PRODUCT_COUNT'], $row['MONTH']); printf("\n"); }} //let's find the sum of product $sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; if($result = $mysqli->query($sql)){ printf("Sum of product: \n"); while($row = mysqli_fetch_array($result)){ printf("Sum of product: %d, MONTH: %s", $row['SUM(PRODUCT_COUNT)'], $row['MONTH']); printf("\n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();
输出
获得的输出如下所示:
Product table created successfully....! First record inserted successfully...! Second record inserted successfully...! Third record inserted successfully...! Fourth record inserted successfully...! Table records: PRODUCT_ID: 101, PRODUCT_NAME: Comb, PRODUCT_COUNT: 2345, MONTH: January PRODUCT_ID: 102, PRODUCT_NAME: Coffee Mugs, PRODUCT_COUNT: 1242, MONTH: January PRODUCT_ID: 103, PRODUCT_NAME: Cutlery, PRODUCT_COUNT: 124, MONTH: January PRODUCT_ID: 101, PRODUCT_NAME: Comb, PRODUCT_COUNT: 3263, MONTH: February Sum of product: Sum of product: 3263, MONTH: February Sum of product: 3711, MONTH: January Sum of product: 6974, MONTH:
var mysql = require('mysql2'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123" }); // Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); // Create a new database sql = "Create Database TUTORIALS"; con.query(sql); sql = "USE TUTORIALS"; con.query(sql); sql = "CREATE TABLE PRODUCT (PRODUCT_ID INT,PRODUCT_NAME VARCHAR(50),PRODUCT_COUNT INT,MONTH VARCHAR(20));" con.query(sql); sql = "INSERT INTO PRODUCT VALUES(101, 'Comb', 2345, 'January'),(102, 'Coffee Mugs', 1242, 'January'),(103, 'Cutlery', 124, 'January'),(101, 'Comb', 3263, 'February'),(102, 'Coffee Mugs', 10982, 'February'),(103, 'Cutlery', 435, 'February');" con.query(sql); sql = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; con.query(sql, function(err, result){ if (err) throw err console.log(result); }); });
输出
获得的输出如下所示:
Connected! -------------------------- [ { 'SUM(PRODUCT_COUNT)': '14680', MONTH: 'February' }, { 'SUM(PRODUCT_COUNT)': '3711', MONTH: 'January' }, { 'SUM(PRODUCT_COUNT)': '18391', MONTH: null } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RollUp { public static void main(String[] args) { String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS"; String user = "root"; String password = "password"; ResultSet rs; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, password); Statement st = con.createStatement(); //System.out.println("Database connected successfully...!"); //create a table with name Product String sql = "CREATE TABLE PRODUCT ( PRODUCT_ID INT, PRODUCT_NAME VARCHAR(50), PRODUCT_COUNT INT, MONTH VARCHAR(20) )"; st.execute(sql); System.out.println("Product table created successfully....!"); //let's insert some records into it... String sql1 = "INSERT INTO PRODUCT VALUES(101, 'Comb', 2345, 'January'), (102, 'Coffee Mugs', 1242, 'January'), (103, 'Cutlery', 124, 'January'), (101, 'Comb', 3263, 'February')"; st.execute(sql1); System.out.println("Records inserted successfully...!"); //print table records String sql2 = "SELECT * FROM PRODUCT"; rs = st.executeQuery(sql2); System.out.println("Table records: "); while(rs.next()) { String PRODUCT_ID = rs.getString("PRODUCT_ID"); String PRODUCT_NAME = rs.getString("PRODUCT_NAME"); String PRODUCT_COUNT = rs.getString("PRODUCT_COUNT"); String MONTH = rs.getString("MONTH"); System.out.println("PRODUCT_ID: " + PRODUCT_ID + ", PRODUCT_NAME: " + PRODUCT_NAME + ", PRODUCT_COUNT: " + PRODUCT_COUNT + ", MONTH: " + MONTH); } //let's calculate the sum of product with RollUp String sql3 = "SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP"; rs = st.executeQuery(sql3); System.out.println("Sum of product: "); while(rs.next()) { String sum = rs.getString("SUM(PRODUCT_COUNT)"); String MONTH = rs.getString("MONTH"); System.out.println("Sum: " + sum + ", MONTH: " + MONTH); } }catch(Exception e) { e.printStackTrace(); } } }
输出
获得的输出如下所示:
Product table created successfully....! Records inserted successfully...! Table records: PRODUCT_ID: 101, PRODUCT_NAME: Comb, PRODUCT_COUNT: 2345, MONTH: January PRODUCT_ID: 102, PRODUCT_NAME: Coffee Mugs, PRODUCT_COUNT: 1242, MONTH: January PRODUCT_ID: 103, PRODUCT_NAME: Cutlery, PRODUCT_COUNT: 124, MONTH: January PRODUCT_ID: 101, PRODUCT_NAME: Comb, PRODUCT_COUNT: 3263, MONTH: February Sum of product: Sum: 3263, MONTH: February Sum: 3711, MONTH: January Sum: 6974, MONTH: null
import mysql.connector # Establishing the connection connection = mysql.connector.connect( host='localhost', user='root', password='password', database='tut' ) # Creating a cursor object cursorObj = connection.cursor() # providing rollup query rollup_query = """SELECT SUM(PRODUCT_COUNT), MONTH FROM PRODUCT GROUP BY MONTH WITH ROLLUP""" cursorObj.execute(rollup_query) # Fetching and printing the results results = cursorObj.fetchall() print("Rollup Results:") for row in results: print(f"Product Count: {row[0]}, MONTH: {row[1]}") # Closing the cursor and connection cursorObj.close() connection.close()
输出
获得的输出如下所示:
Rollup Results: Product Count: 14680, MONTH: February Product Count: 3711, MONTH: January Product Count: 18391, MONTH: None