SELECT distinct c.id,
c.authentication_name,
c.customer_no,
c.reg_status,
c.legal_person_name,
c.estiblish_time,
c.credit_code,
c.reg_capital,
c.province_code,
c.province,
c.city_code,
c.city,
c.area_code,
c.area,
c.address,
c.register_time,
c.uniformcode,
c.invitationcode,
c.belong_person,
c.status,
c.door_head_name,
c.clinic_type,
c.doctor_quantity,
c.nurse_quantity,
c.dental_chair_quantity,
c.passenger_flow,
c.business_scope,
c.public_holiday,
c.checkout_type,
c.first_order_time,
c.last_order_time,
c.last_follow_time,
c.mm_sale_amount,
c.suya_order_quantity,
c.tianyancha_update_time,
c.customer_type,
c.create_by,
c.create_time,
c.update_by,
c.update_time,
c.del_flag,
cc.name as primaryContact,
cc.phone as primaryPhone,
su.user_id as belongPersonId,
su.nick_name as belongPerson
from customer c
left join (select id,
customer_id,
name,
phone,
is_primary
from customer_contacts
where is_primary = '1') cc on cc.customer_id = c.id
left join sys_user su on c.invitationcode = su.invitationcode
left join backlog_follow bf on c.customer_no = bf.customer_no
where c.del_flag = '0'
<if test="invitationcodeList != null and invitationcodeList.size() > 0">
and c.invitationcode in (<foreach collection="invitationcodeList" item="i" separator=",">
#{i}
</foreach>)
</if>
<if test="authenticationName != null and authenticationName != ''">
and c.authentication_name like CONCAT('%', #{authenticationName}, '%')
</if>
<if test="regionCodeList != null and regionCodeList.size() > 0">
and (
c.province_code in (<foreach collection="regionCodeList" item="i" separator=",">
#{i}
</foreach>)
or c.city in (<foreach collection="regionCodeList" item="i" separator=",">
#{i}
</foreach>)
)
</if>
<if test="belongPersonId != null">
and su.user_id = #{belongPersonId}
</if>
这段SQL语句中使用了多个左连接会导致查询变慢。可以尝试以下优化方法:
确保表中的列都有适当的索引,以便查询可以更快地执行。可以使用EXPLAIN
命令来查看查询的执行计划,并确定是否使用了索引。
尽可能使用简单的查询,避免使用复杂的子查询或连接查询。可以考虑将左连接改为内连接,以减少查询的执行时间。
数据库结构优化:如果表结构不合理,可能会导致查询变慢。可以考虑使用范式化来减少数据冗余,并确保表中的列具有适当的数据类型。
缓存优化:可以使用缓存来减少查询的执行时间。例如,可以使用Memcached或Redis来缓存查询结果,以便下次查询时可以更快地获取数据。
服务器优化:如果服务器配置不足,可能会导致查询变慢。可以考虑升级服务器硬件或增加服务器数量,以提高查询性能。
这个查询,很明显不需要联查,完全可以做到单表多条件,将逻辑在业务层实现就可以了,而且其中backlog_follow这个表,关联的意义在哪里?