如何在MySQL中一次仅获取N行?
要一次仅获取N行,可以使用LIMIT运算符。以下是语法-
select *from yourTableNameLIMIT 0,N;
让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Name) values('John'); mysql> insert into DemoTable(Name) values('Larry'); mysql> insert into DemoTable(Name) values('Bob'); mysql> insert into DemoTable(Name) values('Sam'); mysql> insert into DemoTable(Name) values('Mike'); mysql> insert into DemoTable(Name) values('David'); mysql> insert into DemoTable(Name) values('Carol'); mysql> insert into DemoTable(Name) values('Ramit'); mysql> insert into DemoTable(Name) values('Adam'); mysql> insert into DemoTable(Name) values('Chris'); mysql> insert into DemoTable(Name) values('Robert'); mysql> insert into DemoTable(Name) values('James'); mysql> insert into DemoTable(Name) values('Jace');
使用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)