[mysql] MySQL IF ELSEIF in select query

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):

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

This question is related to mysql if-statement

The answer is


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..


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.


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/


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

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