标签:一个 stat sele 图片 order by time bsp sys image
记录一个优化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 id="cntPhoneBacks" parameterType="map" resultType="int">
SELECT COUNT(a.id)
FROM tb_phoneback_apply a
<if test="userName != null or userPhone!= null or userEmail != null">
RIGHT JOIN (SELECT id
FROM tb_user
<where>
<if test="userName != null">u.user_name = #{userName}</if>
<if test="userPhone != null">AND u.user_tel = #{userPhone}</if>
<if test="userEmail != null">AND u.user_email = #{userEmail}</if>
</where>
) u ON u.id = a.user_id
</if>
<where>
<if test="handleStatus != null">AND a.`status` = #{handleStatus}</if>
</where>
</select>
标签:一个 stat sele 图片 order by time bsp sys image
原文地址:https://www.cnblogs.com/-xuzhankun/p/13999020.html