Multiple IF statements on MYSQL

╄→尐↘猪︶ㄣ 提交于 2019-12-04 23:35:50

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

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
Siva

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;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!