📜  Node.js MySQL LEFT()函数

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

Node.js MySQL LEFT()函数

LEFT()函数是 MySQL 中的内置函数,用于获取给定字符串的特定大小的前缀。

句法:

LEFT(input_string, size_of_prefix)

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

  • input_string:我们将得到这个输入字符串的前缀
  • size_of_prefix:前缀中的字符数

返回值: LEFT()函数返回一个字符串,它是特定大小的 input_string 的前缀。

模块:

  • mysql:处理 MySQL 连接和查询
npm install mysql

SQL 发布者表预览:

示例 1:静态查询

Javascript
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 LEFT(name, 4) AS prefix_name FROM publishers";
  
  db_con.query(query, (err, rows) => {
    if (err) throw err;
  
    console.log(rows);
  });
});


Javascript
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 ? in below query
  let query = "SELECT LEFT(salary, ?) AS prefix_salary FROM publishers";
  let sizeOfPrefix = 3;
  
  // notice second argument in below function
  db_con.query(query, sizeOfPrefix, (err, rows) => {
    if (err) throw err;
  
    console.log(rows);
  });
});


输出:

示例 2:动态查询

Javascript

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 ? in below query
  let query = "SELECT LEFT(salary, ?) AS prefix_salary FROM publishers";
  let sizeOfPrefix = 3;
  
  // notice second argument in below function
  db_con.query(query, sizeOfPrefix, (err, rows) => {
    if (err) throw err;
  
    console.log(rows);
  });
});

输出: