2025-05-17

使用索引可以提高查詢效率,廢話不多說,先來個例子。

 

Sql代碼:

CREATE TABLE `person` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(20) DEFAULT NULL,  
  `birthday` datetime DEFAULT NULL,  
  `isMan` int(11) DEFAULT NULL,  
  `salary` double DEFAULT NULL,  
  `test` int(11) DEFAULT NULL,  
  PRIMARY KEY (`id`)  
)  
CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `isMan` int(11) DEFAULT NULL,
  `salary` double DEFAULT NULL,
  `test` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

 

 在插入一些數據。例如:


 

運行:

EXPLAIN select name from person where name='linjia4'

觀察結果:



 row=23是因為這個表總共有23條記錄,即是說做瞭全表掃描

 

在搜索的“name”加上索引:

create index testtest on person (name)

再執行EXPLAIN select name from person where name='linjia4'

觀察結果:



 rows=1,即是所當查詢語句執行時通過name的索引,直接定位到那條數據,不用做全表掃描

 

索引的效果是顯而易見的,大大的提高瞭查詢的速度。但索引也不能濫用,增加索引是要付出代價的。

 

接下來的文章會介紹索引更深層次的知識,我希望通過自己的理解,用一種簡單易懂的方式闡述知識

摘自:鄰傢的技術倉庫

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *