如何使用联接在mysql中使用case语句?

时间:2018-11-21 07:41:43

标签: mysql sql

我正在研究产品和类别以及产品折扣。我已经做了产品折扣。但是问题出在计算category_discount。这是我的代码:

SELECT products.id, products.product_name, products.product_price, products.product_discount, categories.category_discount,
(CASE WHEN products.product_discount = 0  THEN products.product_price
      WHEN products.product_discount != 0 THEN products.product_price - ( products.product_price *  products.product_discount)/100
      WHEN categories.category_discount !=0 THEN products.product_price - ( products.product_price *  categories.category_discount)/100
   END) AS amount
 FROM products
 join 
categories
on products.category_id = categories.id

请参阅下面的结果,它没有为第一行计算category_discount: enter image description here

1 个答案:

答案 0 :(得分:1)

然后按时间顺序评估何时陈述,直到满足一项。 在第一行中,第一个“从句”得到满足,因此没有折扣。请尝试以下操作:

 WHEN products.product_discount = 0  AND categories.category_discount = 0   THEN products.product_price

甚至像这样重新排序:

 SELECT products.id, products.product_name, products.product_price, products.product_discount, categories.category_discount,
 (CASE WHEN products.product_discount != 0 THEN products.product_price - ( products.product_price *  products.product_discount)/100
  WHEN categories.category_discount !=0 THEN products.product_price - ( products.product_price *  categories.category_discount)/100
    ELSE products.product_price
 END) AS amount
 ...