如何一次只从 MySQL 中获取 N 行?
要一次只获取 N 行,可以使用 LIMIT 运算符。以下是语法 -
select *from yourTableNameLIMIT 0,N;
让我们首先创建一个表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20) ); Query OK, 0 rows affected (0.25 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable(Name) values('John'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable(Name) values('Larry'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(Name) values('Bob'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable(Name) values('Sam'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(Name) values('Mike'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(Name) values('David'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable(Name) values('Carol'); Query OK, 1 row affected (0.05 sec) mysql> insert into DemoTable(Name) values('Ramit'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable(Name) values('Adam'); Query OK, 1 row affected (0.03 sec) mysql> insert into DemoTable(Name) values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Name) values('Robert'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable(Name) values('James'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Name) values('Jace'); Query OK, 1 row affected (0.05 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+----+--------+ | Id | Name | +----+--------+ | 1 | John | | 2 | Larry | | 3 | Bob | | 4 | Sam | | 5 | Mike | | 6 | David | | 7 | Carol | | 8 | Ramit | | 9 | Adam | | 10 | Chris | | 11 | Robert | | 12 | James | | 13 | Jace | +----+--------+ 13 rows in set (0.00 sec)
以下是每次只获取 N 行的查询。这里,我们只获取 10 行 -
mysql> select *from DemoTable LIMIT 0,10;
这将产生以下输出 -
+----+-------+ | Id | Name | +----+-------+ | 1 | John | | 2 | Larry | | 3 | Bob | | 4 | Sam | | 5 | Mike | | 6 | David | | 7 | Carol | | 8 | Ramit | | 9 | Adam | | 10 | Chris | +----+-------+ 10 rows in set (0.00 sec)
广告