1. 程式人生 > 實用技巧 >mysql 索引建立

mysql 索引建立

索引的建立

1.建立索引的原則

1.如果可以建立唯一鍵索引,就建立唯一鍵索引
2.為經常需要排序、分組和聯合操作的欄位建立索引
3.為常作為查詢條件的欄位建立索引

4.儘量使用字首索引
	如果索引欄位的值很長,最好使用值的字首來索引。例如,TEXT和BLOG型別的欄位,進行全文檢索
會很浪費時間。如果只檢索欄位的前面的若干個字元,這樣可以提高檢索速度

5.限制索引的數目
	索引的數目不是越多越好。每個索引都需要佔用磁碟空間,索引越多,需要的磁碟空間就越大。
修改表時,對索引的重構和更新很麻煩。越多的索引,會使更新表變得很浪費時間。

6.刪除不再使用或者很少使用的索引
	表中的資料被大量更新,或者資料的使用方式被改變後,原有的一些索引可能不再需要。資料庫管理
員應當定期找出這些索引,將它們刪除,從而減少索引對更新操作的影響。

2.不走索引的情況總結

1)沒有查詢條件,或者查詢條件沒有索引

#查詢所有資料
mysql> explain select * from city;

#刪除索引,然後查詢
mysql> alter table city drop index District_key;
mysql> explain select * from city where District='heilongjiang';

2)查詢結果集是原表中的大部分資料,應該是15%以上

#表中資料一共4079,查詢資料539條,走索引    13.2%
mysql> explain select * from city where population > 500000;

#表中資料一共4079,查詢資料737條,不走索引	18%
mysql> explain select * from city where population > 400000;

3)索引壞了

反覆插入刪除容易損壞索引

4)查詢條件使用了運算子號

#運算子號如果在等號左邊,則不走索引
mysql> explain select * from city where id-1=2;

#運算子號如果在等號右邊,則走索引
mysql> explain select * from city where id=2+1;

5)隱式轉換

# 1.建表
mysql> create table phone(id int,name varchar(10),number varchar(20));

#2.建立索引
mysql> alter table phone add unique key uni_key(number);

#3.插入資料
mysql> insert phone values(1,'警察局',110),(2,'消防',119),(3,'醫院',120);

#4.測試查詢資料是否走索引
1)不走索引
mysql> explain select * from phone where number=120;
2)走索引
mysql> explain select * from phone where number='120';
#因為120存到資料庫中的欄位是字元型別,那麼查詢時字元型別必須加引號

6)使用 like + % 的模糊匹配,當條件以%開頭時

#1. % 在最前面時不走索引
mysql> explain select * from city where countrycode like '%H';
mysql> explain select * from city where countrycode like '%H%';

#2. % 在後面時走索引
mysql> explain select * from city where countrycode like 'H%';

#3. % 在中間時也走索引
mysql> select * from city where countrycode like 'C%N';

7)聯合索引,查詢條件不包含建立聯合索引排第一的欄位時

#0.檢視聯合索引
mysql> show index from user;
+-------+------------+-----------+--------------+-------------+
| Table | Non_unique | Key_name  | Seq_in_index | Column_name |
+-------+------------+-----------+--------------+-------------+
| user  |          1 | index_all |            1 | sex         |
| user  |          1 | index_all |            2 | age         |
| user  |          1 | index_all |            3 | money       |
| user  |          1 | index_all |            4 | look        |
+-------+------------+-----------+--------------+-------------+

#1.只要包含排第一的欄位條件,就走索引
mysql> select * from user where sex='fmale' and age='30';
mysql> explain select * from user where age='30' and money='100000000' and look='beautiful' and sex='fmale';

#2.不包含建立聯合索引排第一的欄位時,不走索引
mysql> explain select * from user where age='30' and money='100000000' and look='beautiful';

8) <> ,not in 不走索引

mysql> explain select * from phone where number not in (110);

mysql> explain select * from phone where number <> '110';