简体   繁体   English

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

[英]how can I write IF statement in mysql

I have a table with type field. 我有一个type字段的表。

how can I check this field in query: 如何在查询中检查此字段:

I want to check it if type == 'a' 如果type =='a',我想检查一下

then bes = amount , bed = '-' 然后bes = amountbed =' - '

ELSE bed = amount , bes = '-' ELSE bed = amountbes =' - '

bes and bed is not really exists in my table but amount is (int) bes和bed在我的表中并不存在但是数量是(int)

this is my try: 这是我的尝试:

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

... my searches wasn't useful ...我的搜索无用

any solution... 解决方案......

You can create condition for every row, MySQL supports inline IF statements. 您可以为每一行创建条件, MySQL支持内联 IF语句。

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

You'll need two case statements for that: 你需要两个案例陈述:

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

One CASE-WHEN-THEN-ELSE can have only one return value... 一个CASE-WHEN-THEN-ELSE只能有一个返回值......

This should do the trick: 这应该做的伎俩:

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

Depending on your MySQL version, you can use IF or one of two different syntaxes for CASE CASE (1), CASE (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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM