Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple IF statements on MYSQL

I'm trying to Display somes values in my database result, I am using this code but I can not succeed:

SELECT item_code, IF(category_code = 'HERR1', 'NO', 1) OR (category_code = 'COLN5', 'NO', 2) AS category_code, item_name, item_quantity FROM qa_items

EDIT : I Want to display for example:

If category_code = 'HERR1'
 Display = 1
else if category_code = 'COLN5'
 Display = 2
End If

If anyone has any idea, would greatly appreciate it

like image 495
John Nuñez Avatar asked Mar 10 '12 17:03

John Nuñez


People also ask

Can you do if statements in MySQL?

The MySQL IF() function is used for validating a condition. The IF() function returns a value if the condition is TRUE and another value if the condition is FALSE. The MySQL IF() function can return values that can be either numeric or strings depending upon the context in which the function is used.

Is there if else in MySQL?

In MySQL, the IF-THEN-ELSE statement is used to execute code when a condition is TRUE, or execute different code if the condition evaluates to FALSE.

Can I use if condition in SQL query?

In MS SQL, IF…ELSE is a type of Conditional statement. Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed.


1 Answers

I'd rather use CASE :

SELECT item_code, 
CASE category_code 
WHEN 'HERR1' THEN 1
WHEN 'COLN5' THEN 2
ELSE 'NO'
END as category_code, item_name, item_quantity 
FROM qa_items

But IF will also work : IF(category_code='HERR1',1, IF(category_code='COLN5',2,'NO'))

like image 83
a1ex07 Avatar answered Oct 11 '22 01:10

a1ex07