📜  NodeJS MySQL 按条款排序

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

NodeJS MySQL 按条款排序

简介:我们使用 SQL ORDER BY 子句根据某个列值按升序或降序对数据进行排序。

句法:

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



npm install mysql

数据库:我们的 SQL用户表预览与示例数据如下所示:

示例 1:从 users 表中选择所有列,但按名称升序排序。

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");
  
    // Our Query
    let query = 'SELECT * FROM users ORDER BY name';
  
    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");
  
    // Notice the address column and DESC below
    let query = 'SELECT address FROM users ORDER BY name DESC';
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});


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

node index.js

输出:

示例2:仅从users 表中选择地址列,但按名称降序排列。

索引.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");
  
    // Notice the address column and DESC below
    let query = 'SELECT address FROM users ORDER BY name DESC';
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

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

node index.js

输出: