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

标签 mysql sql database

SELECT id, amount FROM report

我需要 amount成为 amount如果 report.type='P'-amount如果 report.type='N' .如何将其添加到上述查询中?

最佳答案

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)部分表示当amount不为null时返回amount else return 0

关于mysql - 'SELECT' 语句中的 'IF' - 根据列值选择输出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5951157/

相关文章:

php - 如何组合多对多表中所有值的 select 语句

php - 同时在laravel中插入记录多对多关系

sql - 相对于表中相似行的数量向行添加计数

php - 检查值是否介于两列的值之间

javascript - 通过在 php 中使用来自 mysql 的数据在谷歌地图上显示标记

mysql - 如何更正 MySql 表中递增值的重置

sql - 在已删除行的查询中使用 SUM 函数

sql - 数据库结构 - 如何将用户链接到工作?

php - 使用 memcached 作为聊天消息的数据库缓冲区

java - SQLite 删除不工作