[MySQL]MySQL数据库中如何使用IF判断语句查询基于列值的结果?
问题描述
比如有以下数据表(report)的查询语句:
SELECT id, amount,type FROM report
需要查询的是根据 report
表的 type
字段进行判断,如果 type='P'
则 amount
为:amount,如果 type='N'
则 amount
为:-amount ,在MySQL语句中如何使用判断实现呢?
方案一
SELECT id,
IF(type = 'P', amount, amount * -1) as amount
FROM report
如果需要处理 null
值,则:
SELECT id,
IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM report
方案二
select id,
case report.type
when 'P' then amount
when 'N' then -amount
end as amount
from
`report`
方案三
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
方案五
SELECT
id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM report
方案六
SELECT id, amount
FROM report
WHERE type='P'
UNION
SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'
ORDER BY id;
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册