我怎样才能在mysql中编写IF语句

时间:2013-03-11 13:26:26

标签: mysql sql if-statement

我有一个包含type字段的表格。

如何在查询中检查此字段:

如果type =='a'

,我想检查一下

然后bes = amountbed =' - '

ELSE bed = amountbes =' - '

在我的桌子里,bes和bed并不存在但是数量是(int)

这是我的尝试:

SELECT billing.*,
    CASE billing.type WHEN 'A' THEN billing.amount AS bes, '-' AS bed ELSE billing.amount AS bed, '-' AS bes END
    FROM billing

...我的搜索无效

任何解决方案......

5 个答案:

答案 0 :(得分:5)

您可以为每一行创建条件,MySQL支持内嵌 IF语句。

SELECT billing.*,
       IF(billing.type = 'A', billing.amount, '-') AS bes,
       IF(billing.type = 'A', '-', billing.amount) AS bed
FROM   billing

答案 1 :(得分:4)

你需要两个案例陈述:

SELECT billing.*,
  CASE billing.type WHEN 'A' THEN billing.amount ELSE '-' AS bes END,
  CASE billing.type WHEN 'A' THEN '-' ELSE billing.amount AS bed END
FROM billing

答案 2 :(得分:3)

一个CASE-WHEN-THEN-ELSE只能有一个返回值......

这应该可以解决问题:

SELECT billing.*,
CASE billing.type WHEN 'A' THEN billing.amount ELSE '-' END AS bes,
CASE billing.type WHEN 'A' THEN '-' ELSE billing.amount END AS bed 
FROM billing

答案 3 :(得分:3)

SELECT billing.*,
    CASE  WHEN billing.type =  'A' THEN billing.amount ELSE 0 END AS bes,
    CASE  WHEN billing.type <> 'A' THEN billing.amount ELSE 0 END AS bed
FROM billing

答案 4 :(得分:2)

根据您的MySQL版本,您可以使用IFCASE CASE(1),CASE(2)的两种不同语法之一。

SELECT *,
  (IF type = 'A' THEN amount ELSE '-' END IF) bes,
  (IF type = 'A' THEN '-' ELSE amount END IF) bed
FROM billing