fxu*_*ser 2 mysql sql indexing
SQL:
SELECT
COUNT(usr.id) as `total_results`
FROM
users as usr
LEFT JOIN profile as prof
ON prof.uid = usr.uid
WHERE
usr.username LIKE '%a%'
OR
prof.name LIKE '%a%'
Run Code Online (Sandbox Code Playgroud)
用户索引:
uid - uid
username - username
Run Code Online (Sandbox Code Playgroud)
个人资料的索引
index1 - uid
index2 - uid,name
index3 - name
Run Code Online (Sandbox Code Playgroud)
说明:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY usr ALL NULL NULL NULL NULL 18387
1 PRIMARY prof ref index2,index1 index2 8 site.usr.uid 1 Using where
2 DEPENDENT SUBQUERY sub ref i3,index1,index2 i3 16 site.usr.uid,const 1 Using index
Run Code Online (Sandbox Code Playgroud)
上面的查询大约需要0.1221
我怎样才能让它跑得更快?
要匹配的字符串开头的%使得它无法使用索引.开头的通配符使索引无效,MySQL必须在每一行的该列中进行搜索.它不能跳过.如果您知道要搜索的项目位于字段开头的开头,则可以删除开头'%'.
但是,如果你正在寻找'史蒂夫',我的回答将是'steve','steven','steve-boss',而不是'boss-steve'或'realsteve'.