好用的 sql 内置函数

在 mapper 中写 sql 的时候,能够用到的 sql 内置函数:sql

1. now()app

对于 insert , "create_time" 的值改成 "now()","update_time" 的值改成 "now()";函数

对于 update , "update_time" 的值改成 "now()"。spa

<update id="checkedOrUncheckedProduct" parameterType="map">
    update immall_cart
    set checked = #{checked},
    update_time = now()
    where user_id = #{userId}
    <if test="productId != null">
        and product_id = #{productId}
    </if>
</update>

update 语句,set 多个参数的时候,记得要用 "," 分隔,不然语句错误。it

 

2. IFNULL()test

<select id="selectCartProductCount" resultType="int" parameterType="int">
    select IFNULL(sum(quantity),0) as count
    from immall_cart
    where user_id = #{userId}
</select>

若是 sum 为 null,是不能够传给基本类型 int 的;若是更改返回值类型 int 为 Integer 则又会在 service层报错。怎么办呢?date

咱们当时是不但愿发生报错的啊,利用 IFNULL()函数,赋予一个默认值0,当 sum(quantity) 为 null 时,返回默认值。这样就解决了。select

相关文章
相关标签/搜索