📜  Node.js MySQL AVG()函数

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

Node.js MySQL AVG()函数

我们使用 AVG函数来获取 MySQL 表给定列中所有行的平均值。

句法:

AVG([column_name])

参数: AVG()函数接受上面提到的和下面描述的单个参数。

  • 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 AVG(salary) AS avg_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 AVG(salary) AS avg_salary 
                 FROM publishers WHERE id < 8";
  
    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 AVG(salary) AS avg_salary 
                 FROM publishers WHERE id < 8";
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

使用以下命令运行index.js文件。

node index.js

输出: