好用的 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

相關文章
相關標籤/搜索