初始 sql
select *
from temp_config_value
WHERE
id in (
select max(id) `id`from temp_config_value
where del_flag = 0
group by temp_id, config_id
)
-- select max(id) `id`from temp_config_value where del_flag = 0 group by temp_id, config_id
-- 获取需求分组后最大的id(且以del_flag = 0保证数据的有效性)
-- 分组后最大的id,是分组后最新数据id的变体;根据数据库id自增规则(配置好条件后,几乎等同)
-- 故,可获取所需结果集的id,后续即为基本操作。
结合业务进一步优化:
select *
from temp_config_value
WHERE
id in (
select max(id) `id`from temp_config_value
where del_flag = 0 and identification = 0
group by temp_id, config_id
)
ORDER BY create_time DESC
-- identification = 0 是否是最终结果集:0-是 1-否
项目中具体的 sql:
<!-- 根据业务模板、业务模板功能配置分组查询业务模板功能配置(当前组最新的)结果集List -->
<select id="queryTempConfigValueByGroup" resultMap="TempConfigValueVOResultMap">
SELECT
tcv.id, tcv.temp_id, tcy.name AS tempName, tcv.config_id, tcg.name AS configName ,tcv.date_source_type, tcv.date_source_id, tcv.calculate_type, tcv.calculate_id,
tcv.value, tcv.identification, tcv.sort, tcv.status, tcv.create_time, tcv.update_time, tcv.del_flag
FROM temp_config_value tcv
LEFT JOIN temp_currency tcy ON tcy.id = tcv.temp_id
LEFT JOIN temp_config tcg ON tcg.id = tcv.config_id
<where>
tcv.id IN ( SELECT max(id) `id` FROM temp_config_value WHERE del_flag = 0 AND identification = 0 GROUP BY temp_id, config_id )
AND tcv.del_flag = 0 AND tcv.status = 0
<if test="tempConfigValueDTO.tempId != null and tempConfigValueDTO.tempId != '' ">
AND tcv.temp_id = #{tempConfigValueDTO.tempId}
</if>
</where>
ORDER BY tcv.create_time DESC
</select>
结果测试:
版权声明:本文为weixin_43755082原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。