简体   繁体   English

如何在MySQL中使用if else子查询

[英]how to use if else subquery in mysql

SELECT IF{ 
    (select sum(amount) 
     from bank_credit 
     where bank_name='IDBI') - 
    (select sum(amount) 
     from bank_debit 
     where bank_name='IDBI') as idbi == NULL} 
 else {
     select sum(amount) 
     from bank_credit 
     where bank_name='IDBI')
} as idbi

how to solve this sub query with if else in mysql... plz help some one 如何解决这个子查询,如果在MySQL中...否则PLZ帮助一些

You can use the function ifnull() to convert the NULL to a 0 and just calculate with that. 您可以使用函数ifnull()NULL转换为0然后使用该函数进行计算。

SELECT 
  IFNULL(
    ( SELECT SUM(amount) 
        FROM bank_credit 
        WHERE bank_name='IDBI'
    ), 0
  )
  - 
  IFNULL(
    (
      SELECT SUM(amount) 
        FROM bank_debit 
        WHERE bank_name='IDBI' 
    ), 0
  ) AS idbi;

See also https://stackoverflow.com/a/1441358/1331451 . 另请参阅https://stackoverflow.com/a/1441358/1331451


Take a look at the behaviour of the isnull() with this query: 看一下此查询的isnull()行为:

select 
  ifnull( (select 1), 0)    - ifnull( (select 1), 0)    as 1_1,
  ifnull( (select 1), 0)    - ifnull( (select 0), 0)    as 1_0,
  ifnull( (select 1), 0)    - ifnull( (select NULL), 0) as 1_NULL,
  ifnull( (select 0), 0)    - ifnull( (select 1), 0)    as 0_1,
  ifnull( (select NULL), 0) - ifnull( (select 1), 0)    as NULL_1,
  ifnull( (select NULL), 0) - ifnull( (select NULL), 0) as NULL_NULL
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM