Question

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

Was it helpful?

Solution

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

OTHER TIPS

You need to nest the 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 the first if will fail and the nested if will evaluate

Is this 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

Try the following

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

Kindly Use It Simple It Works.

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

In my 3 columns table, one is package_price, employee_percentage, reference_customer_id.

Now I want if reference_customer_id > 0 then employee percentage as referenced_commission and if reference_customer_id = 0 then direct commission. I tried below way:

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

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

create table student(marks int,grade char);

insert into student values(200,null),(120,null), (130,null);

UPDATE student a INNER JOIN (select s.marks, IF(s.marks>=200,'A',IF(s.marks>=130,'B','P')) AS Grade from student s) b on a.marks= b.marks SET a.Grade = b.Grade;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top