dragon321723 2013-12-19 02:53
浏览 136
已采纳

带有加法运算符的MySQL中的IF / ELSE语句

I have been trying to understand doing this in MySQL but have to admit defeat even after reading several tutorials and the manual on it. Any help would be gratefully appreciated.

I have three fields of decimal type (for currency). These are 'base_price', 'discounted_price' and 'extras_price'.

I am trying to create the MYSQL needed to complete the following pseudo-code:

if (discounted_price is not null or 0) {
    total_price = discounted_price + extras_price
} else {
    total_price = base_price + extras_price
}

It may be worthy of note that this will be used to create a virtual field for CakePHP 2.* Thanks for any help you can offer.

  • 写回答

1条回答 默认 最新

  • dptj13337 2013-12-19 03:03
    关注

    Is this what you are looking for?

    select (case when discounted_price is not null and discounted_price <> 0
                 then discounted_price + extras_price
                 else base_price + extras_price
            end) as total_price
    from t;
    

    By the way, the first condition is redundant in SQL. You can write this as:

    select ((case when discounted_price <> 0 then discounted_price else base_price end) +  
            extras_price) as total_price
    from t;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的