MYSQL上的多个IF语句

时间:2012-03-10 17:19:10

标签: mysql if-statement multipleselection

我正在尝试在我的数据库结果中显示某些值,我正在使用此代码,但我无法成功:

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

编辑: 我想显示例如:

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

如果有人有任何想法,会非常感激

7 个答案:

答案 0 :(得分:27)

我宁愿使用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

IF也适用:IF(category_code='HERR1',1, IF(category_code='COLN5',2,'NO'))

答案 1 :(得分:6)

您需要嵌套if语句

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

然后第一个if将失败,嵌套if将评估

答案 2 :(得分:5)

这是你追求的吗?

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

答案 3 :(得分:1)

尝试以下

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

答案 4 :(得分:0)

在我的3列表中,一个是package_price, employee_percentage, reference_customer_id

现在我希望reference_customer_id > 0然后员工百分比为referenced_commission,如果reference_customer_id = 0则直接佣金。我尝试了以下方式:

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

答案 5 :(得分:0)

请简单使用它。

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

答案 6 :(得分:0)

您可以尝试一下。 在选择查询中使用IF并更新所需的表;)

创建学生表(标记int,grade char);

插入学生值(200,null),(120,null), (130,null);

更新学生a 内部联接(选择s.marks,IF(s.marks> = 200,'A',IF(s.marks> = 130,'B','P'))AS NullPointerException从学生s)b在a.marks = b.marks上 设置a.Grade = b.Grade;