📜  Node.js MySQL Count()函数

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

Node.js MySQL Count()函数

我们使用 MySQL 中的 COUNT()函数来计算满足 WHERE 子句的列中的行数。

句法:

COUNT([column_name])

参数: COUNT()函数接受单个参数,如上所述和如下所述。

  • column_name:我们必须从中返回计数值的列的名称。

模块安装:使用以下命令安装mysql模块:

npm install mysql

数据库:我们的带有示例数据的 SQL发布者表预览如下所示:

示例 1:计算 id 大于 5 的发布者

index.js
const mysql = require("mysql");
  
let db_con  = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: '',
    database: 'gfg_db'
});
  
db_con.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // Here is the query
    let query = "SELECT COUNT(id) AS id_count FROM publishers WHERE id > 5";
  
    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.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // Here is the query
    let query = "SELECT COUNT(salary) AS salary_count FROM 
                 publishers WHERE salary BETWEEN 5000 AND 10000";
  
    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.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // Here is the query
    let query = "SELECT COUNT(salary) AS salary_count FROM 
                 publishers WHERE salary BETWEEN 5000 AND 10000";
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

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

node index.js

输出: