MySQL IF ELSEIF in select query

后端 未结 5 1988
無奈伤痛
無奈伤痛 2020-12-22 23:33

I\'m trying to select different prices of a product based on the quantity that user chooses. This is the query I\'m working on (it has a syntax error):

 sele         


        
5条回答
  •  天命终不由人
    2020-12-23 00:17

    You have what you have used in stored procedures like this for reference, but they are not intended to be used as you have now. You can use IF as shown by duskwuff. But a Case statement is better for eyes. Like this:

    select id, 
        (
        CASE 
            WHEN qty_1 <= '23' THEN price
            WHEN '23' > qty_1 && qty_2 <= '23' THEN price_2
            WHEN '23' > qty_2 && qty_3 <= '23' THEN price_3
            WHEN '23' > qty_3 THEN price_4
            ELSE 1
        END) AS total
     from product;
    

    This looks cleaner. I suppose you do not require the inner SELECT anyway..

提交回复
热议问题