'IF'在'SELECT'语句中的作用-根据列值选择输出值。
'IF'在'SELECT'语句中的作用-根据列值选择输出值。
SELECT id, amount FROM report
如果report.type=\'P\'
,则需要将 amount
设为 amount
,如果report.type=\'N\'
,则需要将-amount
设为amount
。如何将此项添加到以上查询中?
admin 更改状态以发布 2023年5月23日
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。
此外,您还可以处理条件为空的情况。对于空值金额:
SELECT id, IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM report
部分代码IFNULL(amount,0)
的意思是,当金额不为空时返回金额,否则返回0。