小编典典

'SELECT'语句中的'IF'-根据列值选择输出值

mysql

SELECT id, amount FROM report

我需要的amountamount,如果report.type='P'-amount如果report.type='N'。如何将此添加到上面的查询中?


阅读 334

收藏
2020-05-17

共1个答案

小编典典

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

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

此外,您可以处理条件为null的情况。如果为零:

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

该部分IFNULL(amount,0)表示 当金额不为null时返回金额,否则返回0

2020-05-17