1. 程式人生 > >MySQL 中 的IFNNULL 和IF 函式

MySQL 中 的IFNNULL 和IF 函式

MySQL 中 的IFNNULL 和IF 函式

最近在工作中遇到一個問題,專案需求是要求做一個面板,前端像我傳遞id,我通過id去資料庫查詢
得到想要的一些資料,但是實際中會有一些id查詢不到資料,這個時候學到了一個新的mysql函式IFNULL 和IF
當查詢的不到的欄位想要返回0而不是想沒有資料時,我用了IFNULL(expression1,expression2)
當結果是null,返回expression1,不為null返回expression2;
同理好友IF(expression1,expression2,expression3);
如果expression1為true,則執行expression2;否則執行expression3;
sql中的連表查詢也要注意,主表的資料一定要小,可以用子查詢的結果作為主表,從而提高效率

舉個栗子

<select id="selectDemandCurrencyQuantity"
            resultType="com.hzt.trade.dashboard.domain.vo.DashboardAchievementPieCurrencyVO">
        SELECT brand.id brandId, IFNULL(SUM(demand.quantity), 0) AS "quantity",
        IF(currency.code = 'CNY' OR currency.code = 'USD', currency.code, 'OTHER') AS "currencyCode",
        IF(currency.code = 'CNY' OR currency.code = 'USD', currency.name, '其他') AS "currencyName"
        FROM (
          SELECT id, product_id, demand_type, quantity, currency
          FROM hzt_trade.trade_demand
          WHERE ent_id = #{condition.entId,jdbcType=BIGINT}
          AND update_time &gt;
= #{condition.beginDate,jdbcType=TIMESTAMP} AND update_time &lt;= #{condition.endDate,jdbcType=TIMESTAMP} AND is_deleted = 0 AND demand_type IN (1,2) AND parent_id IS NOT NULL AND sale_contract_code IS NOT NULL ) demand LEFT JOIN hzt_config.system_currency currency ON currency.id = demand.currency LEFT JOIN hzt_config.base_product product ON product.id = demand.product_id LEFT JOIN hzt_config.system_brand brand ON brand.id = product.brand WHERE brand.id = #{condition.brandId,jdbcType=BIGINT} GROUP BY currencyCode </
select
>