mysql join count 优化案例

Posted xuzhankun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql join count 优化案例相关的知识,希望对你有一定的参考价值。

记录一个优化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>

 

以上是关于mysql join count 优化案例的主要内容,如果未能解决你的问题,请参考以下文章

mysql 优化例子:IN 换 INNER JOIN

MySQL索引优化(索引三表优化案例)

MySQL的JOIN:JOIN优化实践之内循环的次数

clickhouse,数据查询与写入优化,分布式子查询优化,外部聚合/排序优化,基于JOIN引擎的优化,SQL优化案例,物化视图提速,查询优化常用经验法则,选择和主键不一样的排序键,数据入库优化(代码

优化一个mysql语句

mysql force index 优化案例