偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

MySQL 索引失效的幾種類型以及解決方式

數(shù)據(jù)庫(kù) MySQL
MySQL索引失效的情況有哪些呢?本文就列舉下面七種類型以及解決方式。

MySQL索引失效的情況有哪些呢?本文就列舉下面七種類型以及解決方式。

1. ?索引列不獨(dú)立

是指被索引的這列不能是表達(dá)式的一部分,不能是函數(shù)的參數(shù),比如下面的這種情況:

select id,name,age,salary from table_name where salary + 1000 = 6000;

salary 列被用戶表達(dá)式的計(jì)算了,這種情況下索引就會(huì)失效,解決方式就是提前計(jì)算好條件值,不要讓索引列參與表達(dá)式計(jì)算。

索引字段作為函數(shù)的參數(shù):

select id,name,age,salary from table_name where substring(name,1,3)= 'luc';

解決方式是什么呢,可以提前計(jì)算好條件,不要使用索引,或者可以使用其他的 sql 替換上面的,比如,上面的sql 可以使用 like 來代替:

select id,name,age,salary from table_name where name like 'luc%';

2. 使用了左模糊

select id,name,age,salary from table_name where name like '%lucs%';

平時(shí)盡可能避免用到左模糊,可以這樣寫:

select id,name,age,salary from table_name where name like 'lucs%';

如果實(shí)在避免不了左模糊查詢的話,考慮一下搜索引擎 比如 ES。

3. or 查詢部分字段沒有使用索引

select id,name,age,salary from table_name where name ='lucs' and age >25

這種情況,可以為 name 和 age 都建立索引,否則會(huì)走全表掃描。

4. 字符串條件沒有使用 ''

select id,name,age,salary from table_name where phone=13088772233

上面的這條 sql phone 字段類型是 字符串類型的,但是沒有使用 '13088772233 ', SQL 就全表掃描了,所以字符串索引要使用 ‘’:

select id,name,age,salary from table_name where phone='13088772233 '

5. 不符合最左前綴原則的查詢

例如有這樣一個(gè)組合索引 index(a,b,c):

select * from table_name where b='1'and c='2'
select * from table_name where c='2'

// 上面這兩條 SQL 都是無法走索引執(zhí)行的

最左原則,就是要最左邊的優(yōu)先存在,我不在的話,你們自己就玩不動(dòng)了,除非你自己?jiǎn)为?dú)創(chuàng)立一個(gè)索引,下面這幾條 SQL 就可以走索引執(zhí)行:

select * from table_name where a = 'asaa' and b='1'and c='2'
select * from table_name where a = 'asda' and b='1231'
// 上面這兩條是走索引的,但是下面這條你覺得索引應(yīng)該怎么走,是全部走,還是部分走索引?
select * from table_name where a = 'asda' and c='dsfsdafsfsd'

6. 索引字段沒有添加 not null 約束:

select * from table_name where a is null;
// 這條sql就無法走索引執(zhí)行了,is null 條件 不能使用索引,只能全表掃描了
// mysql 官方建議是把字段設(shè)置為 not null

所以針對(duì)這個(gè)情況,在mysql 創(chuàng)建表字段的時(shí)候,可以將需要索引的字符串設(shè)置為 not null default '' 默認(rèn)空字符串即可

7. 隱式轉(zhuǎn)換

關(guān)聯(lián)表的兩個(gè)字段類型不一致會(huì)發(fā)生隱式轉(zhuǎn)換?:

select * from table_name t1 left join table_name2 t2 on t1.id=t2.tid;
// 上面這條語句里,如果 t1 表的id 類型和 t2 表的tid 類型不一致的時(shí)候,就無法
// 按索引執(zhí)行了。
// 解決方式就是統(tǒng)一設(shè)置字段類型。
責(zé)任編輯:趙寧寧 來源: Java編程鴨
相關(guān)推薦

2025-01-20 00:13:19

TypeScript操作符數(shù)據(jù)類型

2020-12-08 09:45:07

MySQL數(shù)據(jù)庫(kù)索引

2011-12-26 15:58:01

枚舉

2010-03-12 17:29:16

Python模塊

2021-12-20 23:24:40

前端測(cè)試開發(fā)

2024-12-11 08:09:54

2023-02-27 23:45:09

MySQL索引存儲(chǔ)

2020-09-23 07:47:14

Java方式類型

2010-11-24 09:56:20

mysql拷貝表

2010-05-31 12:10:37

2023-09-14 23:14:57

MySQL索引

2022-02-25 14:06:01

區(qū)塊鏈生態(tài)系統(tǒng)技術(shù)

2021-09-09 13:53:08

區(qū)塊鏈加密貨幣技術(shù)

2013-09-02 15:35:00

2024-10-31 09:30:05

線程池工具Java

2020-12-30 07:55:37

C++轉(zhuǎn)換類型

2021-03-11 14:46:05

C++類型轉(zhuǎn)換語言

2022-08-31 07:04:50

Bean作用域

2024-04-19 13:57:30

索引數(shù)據(jù)庫(kù)查詢

2010-10-08 13:53:14

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)