📜  Node.js MySQL 按子句排序

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

Node.js 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 表中选择地址列,但按名称降序排列。

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

输出: