Nested CASE statements in MySQL

放肆的年华 提交于 2019-12-04 22:47:40

You are missing a THEN in your first CASE Statement. (sorry I had to add table aliases)

SELECT sc.session_id
    , sc.product_id
    , sc.product_qty
    , sc.product_option
    , p.product_title
    , p.product_price
    , p.product_sale_price_status
    , p.product_sale_price
    , po.option_text
    , po.option_upcharge
    , CASE
        WHEN (p.product_sale_price_status = 'Y')
        THEN <-- add this
            CASE
            WHEN (po.option_upcharge IS NOT NULL)
                THEN (sc.product_qty * (p.product_sale_price + po.option_upcharge)) 
                ELSE (sc.product_qty * p.product_sale_price)    
            END
        ELSE
            CASE
            WHEN (po.option_upchage IS NOT NULL)
                THEN (sc.product_qty * (p.product_price + po.option_upcharge))
                ELSE (sc.product_qty * p.product_price)
            END
        END AS product_total
FROM tblshopping_cart sc
INNER JOIN tblproducts p
    ON sc.product_id = p.product_id
LEFT JOIN tblproduct_options po
    ON sc.product_option = po.option_product_id
ORDER BY sc.product_qty ASC

It looks like you're missing THEN in the outer CASE:

CASE
WHEN (tblproducts.product_sale_price_status = 'Y') THEN
                                                   ^^^^ add this

I think your problem is the way you write you case.

You missed a THEN after your first when. You also missed a END.

CASE
WHEN (tblproducts.product_sale_price_status = 'Y')
    THEN 
    CASE
    WHEN (tblproduct_options.option_upcharge IS NOT NULL)
        THEN (tblshopping_cart.product_qty * (tblproducts.product_sale_price + tblproduct_options.option_upcharge)) 
        ELSE (tblshopping_cart.product_qty * tblproducts.product_sale_price)    
    END
ELSE
    CASE
    WHEN (tblproduct_options.option_upchage IS NOT NULL)
        THEN (tblshopping_cart.product_qty * (tblproducts.product_price + tblproduct_options.option_upcharge))
        ELSE (tblshopping_cart.product_qty * tblproducts.product_price)
    END
END AS product_total
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!