Node.js MySQL SUM()函数
我们使用 MySQL 中的 SUM()函数来获取某些列的值的总和。
句法:
SUM(column_name)
参数: SUM()函数接受上面提到的和下面描述的单个参数。
- column_name:我们必须从中返回最大值的列名。
模块安装:使用以下命令安装mysql模块。
npm install mysql
数据库:我们的 SQL发布者 带有示例数据的表格预览如下所示:
示例 1:
index.js
const mysql = require("mysql");
let db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'gfg_db'
});
db_con.on('error', (err) => {
console.log(err.code);
});
db_con.connect((err) => {
if (err) {
console.log("Database Connection Failed !!!", err.code);
return;
}
console.log("We are connected to gfg_db database");
// Here is the query
let query = "SELECT SUM(salary) AS total_salary FROM publishers";
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
index.js
const mysql = require("mysql");
let db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'gfg_db'
});
db_con.on('error', (err) => {
console.log(err.code);
});
db_con.connect((err) => {
if (err) {
console.log("Database Connection Failed !!!", err.code);
return;
}
console.log("We are connected to gfg_db database");
// Here is the query
let query = "SELECT SUM(salary) AS total_salary FROM
publishers WHERE id BETWEEN 2 AND 7";
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
使用以下命令运行index.js文件:
node index.js
输出:
示例 2:
index.js
const mysql = require("mysql");
let db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'gfg_db'
});
db_con.on('error', (err) => {
console.log(err.code);
});
db_con.connect((err) => {
if (err) {
console.log("Database Connection Failed !!!", err.code);
return;
}
console.log("We are connected to gfg_db database");
// Here is the query
let query = "SELECT SUM(salary) AS total_salary FROM
publishers WHERE id BETWEEN 2 AND 7";
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
使用以下命令运行index.js文件:
node index.js
输出: