字段 in ()/字段 not in () 中的字段存在null值對(duì)查詢結(jié)果的影響
今天做項(xiàng)目寫sql的時(shí)候绷耍,因?yàn)榇嬖诮M織權(quán)限,需求是想查出組織表中組織id在權(quán)限管理的組織id集合下的澡为,但是父級(jí)的組織id不在管理的組織id下的組織,也就是查出某個(gè)人管理的組織中形成的組織樹的最上級(jí)景埃。因?yàn)樵械墓芾韱T管理的組織樹種媒至,最頂級(jí)的組織的parent_org_id是為null的,所以一開始的想法是這樣的
<if test="isAdminAuth == 'N'.toString()">
<choose>
<when test="orgIds != null and orgIds.size()>0">
and id in
<foreach collection="orgIds" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
and parent_org_id not in
<foreach collection="orgIds" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</when>
<otherwise>
and 1!=1
</otherwise>
</choose>
</if>
<if test="isAdminAuth == 'Y'.toString()">
and parent_org_id is null or parent_org_id=''
</if>
然后谷徙,查詢結(jié)果記錄一條都沒(méi)有拒啰,但是數(shù)據(jù)庫(kù)中的記錄明明有符合條件的
后面才發(fā)現(xiàn),對(duì)于查詢的字段使用in()/not in (),:
查詢的字段包含null的蒂胞,使用in/not in作為條件篩選图呢,不管('a','b','c',null) 中包不包含null,包含這個(gè)字段為null的記錄都不會(huì)被查出來(lái)骗随,也就是該字段為null的話蛤织,該記錄不參與這個(gè)條件的篩選
如果使用not in ( 'a','b','c',null),括號(hào)中包含null鸿染,這個(gè)條件會(huì)直接返回false
后面改為:
<if test="isAdminAuth == 'N'.toString()">
<choose>
<when test="orgIds != null and orgIds.size()>0">
and id in
<foreach collection="orgIds" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
and (parent_org_id not in
<foreach collection="orgIds" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
or parent_org_id is null ) //這里把為null的記錄單獨(dú)查出來(lái)
</when>
<otherwise>
and 1!=1
</otherwise>
</choose>
</if>
<if test="isAdminAuth == 'Y'.toString()">
and parent_org_id is null or parent_org_id=''
</if>
</if>
order by sort is null,sort asc