表用户有大约34k条记录。
我正在启动此查询-
SELECT user_pid, user_fname, user_lname, user_uname, user_mobno, user_email, user_date,
user_userid, user_type, user_status
FROM User
WHERE ((lower(user_fname) like'%all%'
OR lower(user_fname) like'%that%')
OR (lower(user_lname) like'%all%'
OR lower(user_fname) like'%that%'))
AND user_status!=3
AND user_type != 1
LIMIT 20;
解释结果是-
+----+-------------+---------+-------+---------------+-------+---------+------+-------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+-------+---------+------+-------+-------------+
| 1 | SIMPLE | User | range | users | users | 4 | NULL | 16967 | Using where |
+----+-------------+---------+-------+---------------+-------+---------+------+-------+-------------+
表上索引-
用户(用户类型、用户状态)
我应该在哪里添加索引以加快此查询?
最佳答案
这是你的问题
SELECT user_pid, user_fname, user_lname, user_uname, user_mobno,
user_email, user_date, user_userid, user_type, user_status
FROM User
WHERE ((lower(user_fname) like'%all%' or lower(user_fname) like '%that%') or
(lower(user_lname) like'%all%' or lower(user_fname) like '%that%' )
) and user_status!=3 and user_type != 1
limit 20;
首先,仅根据匹配结果的大小(34k中的16k),索引可能无法帮助您。
让我进一步说明。
like
子句是完全通配符搜索。常规索引可用于like
,但仅当模式以非通配符开头时。所有模式都以%
开头,因此常规索引无法工作。你的比较是不平等的比较。再一次,索引很少用于这些。索引最好应用于等式谓词。
我可以预见的唯一索引方案将是名称字段上的全文索引,
user_fname
和user_lname
。我不确定这是否有助于表现,但你可以试试。