Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

mysql - 'SELECT'语句中的'IF' - 根据列值选择输出值('IF' in 'SELECT' statement - choose output value based on column values)

SELECT id, amount FROM report

I need amount to be amount if report.type='P' and -amount if report.type='N' .

(我需要amountamount如果report.type='P'-amount如果report.type='N' 。)

How do I add this to the above query?

(如何将其添加到上述查询中?)

  ask by Michael translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
SELECT id, 
       IF(type = 'P', amount, amount * -1) as amount
FROM report

See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html .

(请参阅http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html 。)

Additionally, you could handle when the condition is null.

(此外,您可以在条件为null时进行处理。)

In the case of a null amount:

(在空金额的情况下:)

SELECT id, 
       IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM report

The part IFNULL(amount,0) means when amount is not null return amount else return 0 .

(部分IFNULL(amount,0)表示金额不为空时返还金额,否则返回0 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...