您可以使用 "LIMIT" 语句限制从查询返回的记录数:
选择 "customers" 表中的前 5 条记录:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers
LIMIT 5";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
运行示例 »
将上面的代码保存在名为 "demo_db_limit.js" 的文件中并运行该文件:
运行"demo_db_limit.js"
C:\Users\
Your Name>node demo_db_limit.js
这会给你这个结果:
[
{ id: 1, name: 'John', address: 'Highway 71'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'}
]
如果要返回 5 条记录,从第三条记录开始,可以使用 "OFFSET" 关键字:
从位置3开始,返回接下来的5条记录:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers
LIMIT 5 OFFSET 2";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
运行示例 »
笔记:"OFFSET 2",表示从第三个位置开始,而不是第二个!
将上面的代码保存在名为 "demo_db_offset.js" 的文件中并运行该文件:
运行"demo_db_offset.js"
C:\Users\
Your Name>node demo_db_offset.js
这会给你这个结果:
[
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'}
]
您还可以像这样编写 SQL 语句"LIMIT 2, 5",它返回与上面的偏移量示例相同的结果:
从位置3开始,返回接下来的5条记录:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers
LIMIT 2, 5";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
运行示例 »
笔记:数字颠倒过来:"LIMIT 2, 5" 与 "LIMIT 5 OFFSET 2" 相同
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!