请大佬帮忙看看这段sql还能怎么优化一下,目前看group by还是有问题,执行计划看group by还是有问题的。。。
select
c.code as deptCode,
a.item_id as itemId,
a.item_code as itemCode,
sum(a.adjust_num) as adjustNum,
0 as status,
group_concat(a.id separator '-') as detailIds,
c.detail_reason as reasonCode
from 表 a,表 c
where c.ware_id = #{wareId}
and a.ware_id = #{wareId}
and c.id = a.adjust_id
and a.gmt_modified between #{Start} and #{End}
and a.status = 2
and c.describe = #{describe}
and (c.source_mode is null or c.source_mode = 14)
<if test="itemCode != null">
and a.item_code = #{itemCode}
</if>
<if test="deptCode != null">
and c.dept_code = #{deptCode}
</if>
<if test="deptCodes != null and deptCodes.size > 0">
and c.dept_code in
<foreach item="iDeptCode" collection="deptCodes" open="(" separator="," close=")">
#{iDeptCode}
</foreach>
</if>
<if test="excludeDetailIds != null and excludeDetailIds.size > 0">
and a.id not in
<foreach item="iExcludeDetailId" collection="excludeDetailIds" open="(" separator="," close=")">
#{iExcludeDetailId}
</foreach>
</if>
<if test="reasonCode != null">
and c.detail_reason = #{reasonCode}
</if>
group by c.dept_code,a.item_code
执行计划:第一行是表c,第二行是表a
https://ask.csdn.net/questions/1064988 一样的问题
select 的非聚合字段需要都出现在 group by 里边,,现在这样查出来的 没group字段值会变的,这个sql 如果放oracle 里的话就报错了,先改下吧
1.先把条件的顺序调一调,根据SQL条件的执行顺序,尽量优先过滤索引字段,其次函数尽量放在最后
2.group by写的是有问题的,如果是在mysql的严格模式,是会报错的