MySQL 整數型別列的索引?


在你的表中有大量記錄時,針對整數型別列新增索引是加快查詢速度的不錯選擇。

如果你的表中記錄較少,那麼在整數型別列上使用索引並不是一個好選擇。

為了理解這個概念,讓我們建立一個表。建立表的查詢如下 −

mysql> create table indexOnIntColumnDemo
   -> (
   -> UserId int,
   -> UserName varchar(20),
   -> UserAge int,
   -> INDEX(UserId)
   -> );
Query OK, 0 rows affected (0.85 sec)

現在檢查表的描述 −

mysql> desc indexOnIntColumnDemo;

以下是輸出 −

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| UserId   | int(11)     | YES  | MUL | NULL    |       |
| UserName | varchar(20) | YES  |     | NULL    |       |
| UserAge  | int(11)     | YES  |     | NULL    |      |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.04 sec)

現在你可以使用插入命令在表中插入一些記錄。查詢如下 −

mysql> insert into indexOnIntColumnDemo values(1001,'John',23);
Query OK, 1 row affected (0.22 sec)
mysql> insert into indexOnIntColumnDemo values(1002,'Sam',25);
Query OK, 1 row affected (0.14 sec)
mysql> insert into indexOnIntColumnDemo values(1003,'Carol',22);
Query OK, 1 row affected (0.24 sec)
mysql> insert into indexOnIntColumnDemo values(1004,'Mike',26);
Query OK, 1 row affected (0.14 sec)

現在你可以使用選擇語句顯示錶中的所有記錄。查詢如下 −

mysql> select *from indexOnIntColumnDemo;

以下是輸出 −

+--------+----------+---------+
| UserId | UserName | UserAge |
+--------+----------+---------+
| 1001   | John     |      23 |
| 1002   | Sam      |      25 |
| 1003   | Carol    |      22 |
| 1004   | Mike     |      26 |
+--------+----------+---------+
4 rows in set (0.00 sec)

為了更快地執行它,對整數型別的索引列使用條件

mysql> select *from indexOnIntColumnDemo where UserId=1004;

輸出如下

+--------+----------+---------+
| UserId | UserName | UserAge |
+--------+----------+---------+
| 1004  | Mike      | 26      |
+--------+----------+---------+
1 row in set (0.00 sec)

更新於: 30-Jul-2019

536 次瀏覽

開啟你的 職業生涯

完成課程來獲得認證

開始
廣告
© . All rights reserved.