📜  Node.js MySQL 限制条款

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

Node.js MySQL 限制条款

LIMIT 子句用于设置 SQL Query 输出的最大行数。

句法:

  • 从用户表的第一行中仅选择 3 行。
    SELECT * FROM users LIMIT 3
  • 从 users 表的第 2 行中仅选择 3 行。
    SELECT * FROM users LIMIT 3 OFFSET 1

模块:

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

SQL用户表预览:

示例 1:从 users 表的第一行中选择 3 行

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 our query
    let query = 'SELECT * FROM users LIMIT 3';
  
    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 offset is 3, this means choose from row 4
    let query = 'SELECT * FROM users LIMIT 4 OFFSET 3';
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});


输出:

示例 2:从 users 表的第 4 行中选择 4 行

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 offset is 3, this means choose from row 4
    let query = 'SELECT * FROM users LIMIT 4 OFFSET 3';
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

输出:从第 4 行开始只有 3 行。所以,输出只包含 3 行