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

最近参与项目的时候遇到一些问题,为避免遗忘,写个博客记录一下。

问题一:前台传来的数据以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>
	
    


    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值