MySQL 中 的IFNNULL 和IF 函数

MySQL 中 的IFNNULL 和IF 函数

最近在工作中遇到一个问题,项目需求是要求做一个面板,前端像我传递id,我通过id去数据库查询
得到想要的一些数据,但是实际中会有一些id查询不到数据,这个时候学到了一个新的mysql函数IFNULL 和IF
当查询的不到的字段想要返回0而不是想没有数据时,我用了IFNULL(expression1,expression2)
当结果expression1不是null,返回expression1,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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值