如何从 MySQL 数据库中选择前 10 个元素?
从数据库中使用 SQL ORDER BY 子句 选择前 10 项,带 LIMIT 10。
语法如下
SELECT *FROM yourTableName ORDER BY yourIdColumnName LIMIT 10;
为了理解上述语法,我们先创建一个表。用于 创建表的 查询如下
mysql> create table Clients - > ( - > Client_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > ClientName varchar(20) - > ); Query OK, 0 rows affected (0.51 sec)
使用 INSERT 命令 在表中插入一些记录。
查询如下:
mysql> insert into Clients(ClientName) values('Larry'); Query OK, 1 row affected (0.09 sec) mysql> insert into Clients(ClientName) values('Sam'); Query OK, 1 row affected (0.19 sec) mysql> insert into Clients(ClientName) values('Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into Clients(ClientName) values('David'); Query OK, 1 row affected (0.15 sec) mysql> insert into Clients(ClientName) values('John'); Query OK, 1 row affected (0.17 sec) mysql> insert into Clients(ClientName) values('James'); Query OK, 1 row affected (0.14 sec) mysql> insert into Clients(ClientName) values('Robert'); Query OK, 1 row affected (0.11 sec) mysql> insert into Clients(ClientName) values('Carol'); Query OK, 1 row affected (0.15 sec) mysql> insert into Clients(ClientName) values('Mike'); Query OK, 1 row affected (0.12 sec) mysql> insert into Clients(ClientName) values('Maxwell'); Query OK, 1 row affected (0.27 sec) mysql> insert into Clients(ClientName) values('Chris'); Query OK, 1 row affected (0.23 sec) mysql> insert into Clients(ClientName) values('Ramit'); Query OK, 1 row affected (0.18 sec)
使用 SELECT 语句 从表中显示所有记录。
查询如下:
mysql> select *from Clients;
输出如下:
+-----------+------------+ | Client_Id | ClientName | +-----------+------------+ | 1 | Larry | | 2 | Sam | | 3 | Bob | | 4 | David | | 5 | John | | 6 | James | | 7 | Robert | | 8 | Carol | | 9 | Mike | | 10 | Maxwell | | 11 | Chris | | 12 | Ramit | +-----------+------------+ 12 rows in set (0.00 sec)
以下是对前 10 个元素进行排序的查询
mysql> select *from Clients ORDER BY Client_Id LIMIT 10;
输出如下:
+-----------+------------+ | Client_Id | ClientName | +-----------+------------+ | 1 | Larry | | 2 | Sam | | 3 | Bob | | 4 | David | | 5 | John | | 6 | James | | 7 | Robert | | 8 | Carol | | 9 | Mike | | 10 | Maxwell | +-----------+------------+ 10 rows in set (0.00 sec)
以下是对前 10 个元素进行排序的备选查询。
查询如下:
mysql> select *from Clients limit 0,10;
输出如下:
+-----------+------------+ | Client_Id | ClientName | +-----------+------------+ | 1 | Larry | | 2 | Sam | | 3 | Bob | | 4 | David | | 5 | John | | 6 | James | | 7 | Robert | | 8 | Carol | | 9 | Mike | | 10 | Maxwell | +-----------+------------+ 10 rows in set (0.00 sec)
广告