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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5951157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:49:28  来源:igfitidea点击:

'IF' in 'SELECT' statement - choose output value based on column values

mysqlsqldatabase

提问by Michael

SELECT id, amount FROM report

I need amountto be amountif report.type='P'and -amountif report.type='N'. How do I add this to the above query?

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

回答by Felipe Buccioni

SELECT id, 
       IF(type = 'P', amount, amount * -1) as amount
FROM report

See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html.

请参阅http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

Additionally, you could handle when the condition is null. In the case of a null amount:

此外,您可以在条件为空时进行处理。在金额为空的情况下:

SELECT id, 
       IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM report

The part IFNULL(amount,0)means when amount is not null return amount else return 0.

这部分IFNULL(amount,0)意味着当数量不为空时返回数量否则返回 0

回答by mellamokb

Use a casestatement:

使用case语句:

select id,
    case report.type
        when 'P' then amount
        when 'N' then -amount
    end as amount
from
    `report`

回答by user1210826

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;

回答by sang kaul

select 
  id,
  case 
    when report_type = 'P' 
    then amount 
    when report_type = 'N' 
    then -amount 
    else null 
  end
from table

回答by aWebDeveloper

Most simplest way is to use a IF(). Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.

最简单的方法是使用IF()。是的 Mysql 允许你做条件逻辑。IF 函数需要 3 个参数 CONDITION、TRUE OUTCOME、FALSE OUTCOME。

So Logic is

所以逻辑是

if report.type = 'p' 
    amount = amount 
else 
    amount = -1*amount 

SQL

SQL

SELECT 
    id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM  report

You may skip abs() if all no's are +ve only

如果所有的 no 都是 +ve,你可以跳过 abs()

回答by linitux

SELECT id, amount
FROM report
WHERE type='P'

UNION

SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'

ORDER BY id;

回答by Basant Rules

You can try this also

你也可以试试这个

 SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table