您的位置:首页 > 数据库

整理一下近期项目中使用过的sql技巧

2016-04-29 13:17 405 查看
最近参与项目的时候遇到一些问题,为避免遗忘,写个博客记录一下。

问题一:前台传来的数据以1,2,3,4这种格式的数字的时候,在数据库中进行模糊查询,LIKE CONCAT('%,',#{t},',%'),来查询的时候会出现一些问题,会将查询数字的数据都选出来。因此可以构造一个字段,类似于,CONCAT(",",'1',","),筛选数据的时候 ,使用 AND type2 LIKE CONCAT('%,','1',',%'),这种格式,避免进行模糊查询的时候,出现多余的数据。

使用的mybatis 语句如下:

<select id="queryall" resultType="cn.changhong.aftersale.domain.CustomerStore">
SELECT * FROM (SELECT * ,CONCAT(",",type,",") as type2 FROM  customer_store_service) as total  WHERE 1=1
<if test="address !=null and address != ''">
AND address LIKE CONCAT('%',#{address},'%')
</if>
<if test="province !=null and province != ''">
AND province LIKE CONCAT('%',#{province},'%')
</if>
<if test="city !=null and city != ''">
AND city LIKE CONCAT('%',#{city},'%')
</if>
<if test="area !=null and area != ''">
AND area LIKE CONCAT('%',#{area},'%')
</if>
<if test="type2 !=null and type2 != ''">
<foreach collection="type2" item="t" separator="" index="index" >
AND  type2 LIKE CONCAT('%,',#{t},',%')
</foreach>
</if>




问题二:

在做另一个项目的时候,需要实现将三个表的数据加起来,但是表的字段有写不同,在这种时候,可以构造表的字段,将三个表的字段构造成一致。

三个表的结构如下:

day表


hour表


month表:


我开发的接口是根据sn号按照已有的年份来统计电量,因此可以用left函数进行截取构造相同的字段,使用union all连接三个表,然后求出总电量。

sql如下:

<!-- 年份列表查询(包含年总电量) -->
<select id="queryElectricQuantityBysn" resultType="cn.changhong.socket.entity.ElectricQuantity2">
select sn,sum(kwh) as kwh ,year  from
(select sn,kwh ,year from kwh_month  where sn =#{sn}
union all
select sn,kwh ,left(k.day,4) year from kwh_day k where k.sn =#{sn}
union all
SELECT sn,kwh,left(kh.day,4) year from kwh_hour kh WHERE kh.sn=#{sn}
) f group by f.year,f.sn
order by f.year ASC
</select>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: