MySQL not in踩坑
今天想用not in进行嵌套查询时,从逻辑上本应返回数据的结果却没有返回任何数据,查阅资料后找到原因。
not in中 不能包含null值,如果包含null值 则直接返回空结果集
上代码:
<select id="lastId" parameterType="java.lang.String" resultType="cec.ems.module.entity.AlarmRecord">
select id from tb_area as a where a.parent_ids like CONCAT('%',#{id,jdbcType=VARCHAR},'%')
and a.id not in (select parent_id from tb_area);
</select>
如果嵌套在in中的 parent_id 存在null值 则结果集就直接回返回空
应该写成这样 在后面加一个非空判断就可以避免null值
<select id="lastId" parameterType="java.lang.String" resultType="cec.ems.module.entity.AlarmRecord">
select id from tb_area as a where a.parent_ids like CONCAT('%',#{id,jdbcType=VARCHAR},'%')
and a.id not in (select parent_id from tb_area where parent_id is not null);
</select>