Multiple IF statements for MYSQL

I am trying to show somes values ​​in the results of my database, I am using this code, but I cannot 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 show, for example:

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

If anyone has any idea, I would really appreciate it.

+13
source share
7 answers

I would prefer to 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'))

+30
source

You need to nest if statements

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

Then first, if a failure occurs, and the nested if will evaluate

+9
source

Is that what you were after?

 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 
+5
source

Try to execute

 SELECT item_code, CASE category_code WHEN 'HERR1' THEN 1 WHEN 'COLN5' THEN 0 ELSE 'NONE' END AS category_code, item_name, item_quantity FROM qa_items 
+1
source

In my 3-column table, one is package_price, employee_percentage, reference_customer_id .

Now I want that if reference_customer_id > 0 , then the percentage of the employee was equal to referenced_commission , and if reference_customer_id = 0 , then a direct commission. I tried below path:

 SELECT if(reference_customer_id = 0, sum(((package_price*employee_percentage)/100)) , 0) as direct_commission, if(reference_customer_id > 0, sum(((package_price*employee_percentage)/100)) , 0) as reference_commission 
0
source

Please use it simply, it works.

  SELECT if(reference_customer_id = 0,sum(((package_priceemployee_percentage)/100)),sum(((package_priceemployee_percentage)/100))) as direct_commission 
0
source

You can try this. Use IF in the select query and update the table you want;)

create a student table (marked as int, class char);

insert into student values ​​(200, zero), (120, zero), (130, NULL);

UPDATE Student's INTERNAL CONNECTION (select s.marks, IF (s.marks> = 200, 'A', IF (s.marks> = 130, 'B', 'P')) AS Grade from student s) b to a .marks = b.marks SET a.Grade = b.Grade;

0
source

All Articles