📜  NodeJS MySQL SUM()函数

📅  最后修改于: 2022-05-13 01:56:57.031000             🧑  作者: Mango

NodeJS 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:

索引.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

输出: