1)由於like 'xxx%' 形式是能夠用索引的,因此將like '%xxx%' 轉爲 正反值的like 'xxx%' ;
2)利用冗餘數據解決速度問題;ide
SELECT COUNT('*') AS `__count` FROM `t_mytest_userinfo` WHERE (`c_is_delete` = 0 AND `c_company_id` = 'e0b5df9cb47646ee8cd97237b838e35e' AND (`c_emp_name` LIKE '%張三瘋%' ) )
有個 姓名 列,原來查詢是下面這樣得:函數
`c_emp_name` LIKE '%張三瘋%'
1)在表裏新增一列c_emp_name_re,存放姓名反轉以後得值,好比 '張三' 反轉後 '三張';優化
2)對歷史數據生成反轉值code
UPDATE t_mytest_userinfo SET c_emp_name_re=REVERSE(c_emp_name)
備註: reverse()函數能夠反轉字符串索引
3)而後分別在2個姓名列上創建索引字符串
ALTER TABLE `t_mytest_userinfo` ADD INDEX idx_ename_com (c_emp_name,c_company_id), ADD INDEX idx_enamer_com (c_emp_name_re,c_company_id)
4)改寫SQL條件it
`c_emp_name` LIKE '張三瘋%' OR `c_emp_name_re` LIKE '瘋三張%'
1)優化前 io
SELECT COUNT('*') AS `__count` FROM `t_mytest_userinfo` WHERE (`c_is_delete` = 0 AND `c_company_id` = 'e0b5df9cb47646ee8cd97237b838e35e' AND (`c_emp_name` LIKE '%張三瘋%' ) )
執行計劃:table
id select_type table type possible_keys key key_len ref rows Extra ------ ----------- ----------------- ------ ----------------- ----------------- ------- ----------- ------ ------------------------------------ 1 SIMPLE t_mytest_userinfo ref ix_delete_company ix_delete_company 99 const,const 517170 Using index condition; Using where
執行耗時 : 14.776 sec
傳送時間 : 0.001 sec
總耗時 : 14.777 secclass
2)優化後:
SELECT COUNT('*') AS `__count` FROM `t_mytest_userinfo` WHERE (`c_is_delete` = 0 AND `c_company_id` = 'e0b5df9cb47646ee8cd97237b838e35e' AND (`c_emp_name` LIKE '張三瘋%' OR `c_emp_name_re` LIKE '瘋三張%') )
執行計劃:
id select_type table type possible_keys key key_len ref rows Extra ------ ----------- ----------------- ----------- ---------------------------------------------- ---------------------------- ------- ------ ------ ------------------------------------------------------------- 1 SIMPLE t_mytest_userinfo index_merge ix_delete_company,idx_ename_com,idx_enamer_com idx_ename_com,idx_enamer_com 138,138 (NULL) 8 Using sort_union(idx_ename_com,idx_enamer_com); Using where
執行耗時 : 0.007 sec
傳送時間 : 0.003 sec
總耗時 : 0.011 sec
完畢!