mybatis中union可以用if判断连接,但是<select>中第一个select语句不能被if判断,因此可以从dual表中查询null来凑齐。union如果使用order by排序,那么只能放在最后一个查询语句的位置,并且不能带表名。
<!-- 一址多证纳税人分析表 -->
<select id="yzdznsrlistPage" parameterType="page" resultType="pd">
select * from (
select null NSRSBH,null NSRMC,null ZGSWJ_DM,null ZGSWSKFJ_DM,null SSGLY_DM,null FDDBRXM,null SCJYDZ,null ZCDZ
from dual
<if test="pd.flag==1 or pd.flag==2 or pd.flag==3">
union all <!-- 此处应该使用union all 而不是union,使用union的话会导致查出的数据量不对 -->
</if>
<if test="pd.flag==1 or pd.flag==3">
select NSRSBH,NSRMC,ZGSWJ_DM,ZGSWSKFJ_DM,SSGLY_DM,FDDBRXM,SCJYDZ,ZCDZ
from hx_dj.dj_nsrxx nsr
where nsr.zcdz in (select n.zcdz from (select ns.zcdz,count(1) cnt from hx_dj.dj_nsrxx ns group by ns.zcdz
having count(1) > 1) n)
<if test="pd.swjg != null and pd.swjg != ''">
AND
<foreach collection="pd.swjgs" item="item" open="(" separator="OR" close=")">
nsr.ZGSWSKFJ_DM LIKE '${item}%'
</foreach>
</if>
</if>
<if test="pd.flag==3">
union
</if>
<if test="pd.flag==2 or pd.flag==3">
select NSRSBH,NSRMC,ZGSWJ_DM,ZGSWSKFJ_DM,SSGLY_DM,FDDBRXM,SCJYDZ,ZCDZ
from hx_dj.dj_nsrxx nsrscjy
where nsrscjy.scjydz in (select nscjy.scjydz from (select nsscjy.scjydz,count(1) cnt from hx_dj.dj_nsrxx nsscjy group by nsscjy.scjydz
having count(1) > 1) nscjy)
<if test="pd.swjg != null and pd.swjg != ''">
AND
<foreach collection="pd.swjgs" item="item" open="(" separator="OR" close=")">
nsrscjy.ZGSWSKFJ_DM LIKE '${item}%'
</foreach>
</if>
</if>
) where NSRSBH is not null
</select>
针对本问题有了新的解决方式,上面的解决方法太过复杂。
其实要判断两个select查询语句是否合并,没必要判断union是否需要存在。让union一直保持存在就好,比如传1进来,可以让上面的select查出值,下面的select查出的是null;传2进来,可以让下面的select查出值,上面的select查出的是null。这样就没必要传
3进来了。多增加一列z,字段的值就是1、2,这样来决定两个查询语句是否查出来的值是null。
上面的语句可以改为
select NSRSBH,NSRMC,ZGSWJ_DM,ZGSWSKFJ_DM,SSGLY_DM,FDDBRXM,SCJYDZ,ZCDZ,1 z
from hx_dj.dj_nsrxx nsr
where nsr.zcdz in (select n.zcdz from (select ns.zcdz,count(1) cnt from hx_dj.dj_nsrxx ns group by ns.zcdz
having count(1) > 1) n)
<if test="pd.swjg != null and pd.swjg != ''">
AND
<foreach collection="pd.swjgs" item="item" open="(" separator="OR" close=")">
nsr.ZGSWSKFJ_DM LIKE '${item}%'
</foreach>
</if> and z = '1'
union
select NSRSBH,NSRMC,ZGSWJ_DM,ZGSWSKFJ_DM,SSGLY_DM,FDDBRXM,SCJYDZ,ZCDZ,2 z
from hx_dj.dj_nsrxx nsrscjy
where nsrscjy.scjydz in (select nscjy.scjydz from (select nsscjy.scjydz,count(1) cnt from hx_dj.dj_nsrxx nsscjy group by nsscjy.scjydz
having count(1) > 1) nscjy)
<if test="pd.swjg != null and pd.swjg != ''">
AND
<foreach collection="pd.swjgs" item="item" open="(" separator="OR" close=")">
nsrscjy.ZGSWSKFJ_DM LIKE '${item}%'
</foreach>
</if> and z = '2'