首页 / MySQL / 正文

[MySQL]MySQL数据库中如何使用IF判断语句查询基于列值的结果?

9909 发布于: 2018-01-18 读完约需4分钟

[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;

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: .NET[C#]LINQ查询List集合中所有重复的元素如何实现?

下一篇: C#视频教程之使用Dapper轻松访问SQL Server数据库(核心源码)

本文永久链接码友网 » [MySQL]MySQL数据库中如何使用IF判断语句查询基于列值的结果?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册