天天看點

SQL中遇到 like'%xx%'怎麼優化

技巧

如果你經常需要一個以通配符開頭的查詢,常用的方法是在資料庫中儲存需要查詢的值的反序值。例如,假設你想要找所有以.com 結尾的電子郵件位址,當搜尋 email like '%.com' 時 mysql不能使用索引;而搜尋 reverse_email like reverse('%.com')就可以使用定義在 reverse_email 列上的索引。

reverse(str)

    傳回颠倒字元順序的字元串str。

    mysql> select reverse('abc');

            -> 'cba'

    該函數對多位元組可靠的。

key_len: 4 // int not null

key_len: 5 // int null

key_len: 30 // char(30) not null

key_len: 32 // varchar(30) not null

key_len: 92 // varchar(30) null charset=utf8

mysql> explain select p.* from parent p where p.id not in (select c.parent_id from childc)\g

********************* 1. row ***********************

id: 1

select_type: primary

table: p

type: all

possible_keys: null

key: null

key_len: null

ref: null

rows: 160

extra: using where

********************* 2. row ***********************

id: 2

select_type: dependent subquery

table: c

type: index_subquery

possible_keys: parent_id

key: parent_id

key_len: 4

ref: func

rows: 1

extra: using index

2 rows in set (0.00 sec)

mysql> explain select p.*

-> from parent p

-> left join child c on p.id = c.parent_id

-> where c.child_id is null\g

select_type: simple

extra:

type: ref

ref: test.p.id

extra: using where; using index; not exists

-> where not exists

-> select parent_id from child c where c.parent_id

= p.id)\g