如何从MySQL数据库中选择前10个元素?
要使用SQL ORDER BY子句和LIMIT 10从数据库中选择前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)