记录一个优化sql的实际案例
三张表, 表结构, 索引如下:
tb_phoneback_apply有user_id, handle_userid 索引 以及一个 status 和 create_time组合索引.
----------------------------优化前sql----------------------------
SELECT
a.id,
IFNULL(u.user_name, u.user_tel) AS userName,
u.user_tel AS userPhone,
u.user_email AS userEmail,
a.create_time AS applyTime,
a.phone,
a.`status`,
IFNULL(su.`name`, su.login_name) AS handleUser,
a.handle_time AS handleTime
FROM tb_phoneback_apply a
LEFT JOIN tb_user u ON a.user_id = u.Id
LEFT JOIN tb_sys_user su ON su.id = a.handle_userid
ORDER BY a.`status` DESC, a.create_time DESC
LIMIT 0, 10
----------------------------优化后sql-------------------------------------------------------------------------------------
SELECT
a.id,
IFNULL(u.user_name, u.user_tel) AS userName,
u.user_tel AS userPhone,
u.user_email AS userEmail,
a.create_time AS applyTime,
a.phone,
a.`status`,
IFNULL(su.`name`, su.login_name) AS handleUser,
a.handle_time AS handleTime
FROM
(SELECT id, user_id, handle_userid, create_time, phone, `status`, handle_time
FROM tb_phoneback_apply l
ORDER BY l.`status` DESC, l.create_time DESC
LIMIT 0, 10) a
LEFT JOIN tb_user u ON a.`user_id` = u.`Id`
LEFT JOIN tb_sys_user su ON su.id = a.`handle_userid`
ORDER BY a.`status` DESC, a.create_time DESC
----------------------------count优化前sql----------------------------
----------------------------count优化后sql----------------------------
<select >AND a.`status` = #{handleStatus}</if>
</where>
</select>