zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    157 判断字符串是否没有重复字符
    53 翻转字符串
    671 循环单词
    8 旋转字符串
    39 恢复旋转字符串
    6 合并排序数组 Ⅱ
    64 合并排序数组
    60 搜索插入位置
    141 x的平方根
    TCSRM 593 div2(1000)(dp)
  • 原文地址:https://www.cnblogs.com/-xuzhankun/p/13999020.html
Copyright © 2011-2022 走看看