MYSQL:
1: 使用sum求和时如果不存在该字段的内容显示0而非null
SUM 是SQL语句中的标准求和函数,如果没有符合条件的记录,那么SUM函数会返回NULL,如果想返回的是0而不是Null 需要用到 COALESCE()
COALESCE 函数的意思是返回参数列表中第一个为空的值,该方法允许传入多个参数,该函数也是SQL中的标准函数。
eg: SELECT COALESCE(SUM(field1),0) FROM table1 WHERE field2 > 100
参考博文:https://blog.csdn/hongleidy5000/article/details/6434694
2: 如果某列为空时显示0
ifnull() 函数是MySQL控制流函数之一,它接受两个参数,如果不是NULL
,则返回第一个参数。 否则,IFNULL
函数返回第二个参数。
IFNULL(expression_1,expression_2);
如果expression_1
不为NULL
,则IFNULL
函数返回expression_1
; 否则返回expression_2
的结果。
IFNULL
函数根据使用的上下文返回字符串或数字。
eg : SELECT IFNULL(NULL,'IFNULL function'); -- returns IFNULL function
参考资料: https://www.yiibai/mysql/ifnull.html
3:某一列值大于100则按100呈现
select (case when 分数>100 then 100 else 分数 end) as 分数 from 表名
参考资料:https://zhidao.baidu/question/105150190.html
4:mybatis 插入或者更新
<insert id="updateOrInsertPhone2Email" useGeneratedKeys="true" keyProperty="id" parameterType="com.sa.pojo.Phone2Email" >
<!-- 查看是否存在memberid,如果存在及更新,否则插入 -->
<selectKey keyProperty="count" order="BEFORE" resultType="int">
select count(*) as count from phone2email where phone = #{phone,jdbcType=VARCHAR}
</selectKey>
<!-- 如果大于0则更新 -->
<if test="count>0">
update phone2email set email=#{email,jdbcType=VARCHAR} where phone = #{phone,jdbcType=VARCHAR}
</if>
<!-- 如果等于0则保存 -->
<if test="count==0">
insert into phone2email(phone,email)
values(#{phone,jdbcType=VARCHAR},#{email,jdbcType=VARCHAR})
</if>
</insert>
这里的count要有setter方法,也就是要作为Phone2Email(对象)的属性:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Phone2Email {
private Integer id;
private String phone;
private String email;
private int count;
}
如果没有则会报错:
Caused by: org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'count' in com.sa.pojo.Phone2Email.
参考资料:https://blog.csdn/qq_20867981/article/details/80422824
更多推荐
SQL中一些字段使用的汇总
发布评论