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。
使用 case
语句:
select id,
case report.type
when 'P' then amount
when 'N' then -amount
end as amount
from
`report`
if report.type = 'P' use amount, otherwise use -amount for anything else
。如果不是'P',它不会考虑类型。
SELECT CompanyName,
CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
WHEN Country = 'Brazil' THEN 'South America'
ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;
select
id,
case
when report_type = 'P'
then amount
when report_type = 'N'
then -amount
else null
end
from table
最简单的方法是使用 IF()。是的,Mysql 允许你做条件逻辑。 IF 函数需要 3 个参数 CONDITION、TRUE OUTCOME、FALSE OUTCOME。
所以逻辑是
if report.type = 'p'
amount = amount
else
amount = -1*amount
SQL
SELECT
id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM report
如果所有的不是 +ve,你可以跳过 abs()
SELECT id, amount
FROM report
WHERE type='P'
UNION
SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'
ORDER BY id;
你也可以试试这个
SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table
sql/item_cmpfunc.h 722: Item_func_ifnull(Item *a, Item *b) :Item_func_coalesce(a,b) {}
调用合并IF
语句,有什么问题?