Node.js MySQL 按子句排序
简介:我们使用 SQL ORDER BY 子句对数据按升序或降序对某个列值进行排序。
句法:
SELECT * FROM users ORDER BY name;
This will sort all rows of output in ascending order (by default) with respect to name column.
SELECT address FROM users ORDER BY name DESC;
This will sort all rows of output in descending order with respect to name column but return the data of address.
模块安装:使用以下命令安装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
输出: