MySQL IF ELSEIF in select query

后端 未结 5 1963
無奈伤痛
無奈伤痛 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-22 23:59

    I found a bug in MySQL 5.1.72 when using the nested if() functions .... the value of column variables (e.g. qty_1) is blank inside the second if(), rendering it useless. Use the following construct instead:

    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
    
    0 讨论(0)
  • 2020-12-23 00:00

    For your question :

    SELECT id, 
       IF(qty_1 <= '23', price,
       IF(('23' > qty_1 && qty_2 <= '23'), price_2,
       IF(('23' > qty_2 && qty_3 <= '23'), price_3,
       IF(('23' > qty_2 && qty_3<='23'), price_3,
       IF('23' > qty_3, price_4, 1))))) as total 
    FROM product;
    

    You can use the if - else control structure or the IF function in MySQL.

    Reference:
    http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

    0 讨论(0)
  • 2020-12-23 00:12

    IF() in MySQL is a ternary function, not a control structure -- if the condition in the first argument is true, it returns the second argument; otherwise, it returns the third argument. There is no corresponding ELSEIF() function or END IF keyword.

    The closest equivalent to what you've got would be something like:

    IF(qty_1<='23', price,
      IF('23'>qty_1 && qty_2<='23', price_2,
        IF('23'>qty_2 && qty_3<='23', price_3,
          IF('23'>qty_3, price_4, 1)
        )
      )
    )
    

    The conditions don't all make sense to me (it looks as though some of them may be inadvertently reversed?), but without knowing what exactly you're trying to accomplish, it's hard for me to fix that.

    0 讨论(0)
  • 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..

    0 讨论(0)
  • 2020-12-23 00:18

    As per Nawfal's answer, IF statements need to be in a procedure. I found this post that shows a brilliant example of using your script in a procedure while still developing and testing. Basically, you create, call then drop the procedure:

    https://gist.github.com/jeremyjarrell/6083251

    0 讨论(0)
提交回复
热议问题