【问题标题】:COUNT(*) query In MYSQL return 0 in null casesCOUNT(*) 查询在 MYSQL 中在 null 情况下返回 0
【发布时间】:2021-12-28 09:57:30
【问题描述】:

解决方法也可以通过mysql,如果在Laravel php中无法获取,也可以通过subSelect来解决

我正在通过 LARAVEL PHP 进行编程,但在以下查询中遇到了困难:

$R = collect(\DB::connection('mysql_scipg')
        ->table('producao_email')
        ->selectRaw('dominio,count(*) as qtdR')
        ->where('cod_cliente', $cliente_id)
        ->where('lote',$lote)
        ->where('cod_status','R')
        ->whereIn('dominio',$dominiosL)
        ->groupBy('dominio')
        ->get());
$dominio:
array:10 [ 0 => "gmail.com" 1 => "hotmail.com" 2 => "outlook.com" 3 => "bol.com.br" 4 => "live.com" 5 => "terra.com.br" 6 => "icloud.com" 7 => "ig.com.br" 8 => "hotmail.com.br" 9 => "msn.com" ]

我得到的结果:

  #items: array:4 [
    0 => {#54260
      +"dominio": "bol.com.br"
      +"qtdR": 2
    }
    1 => {#54261
      +"dominio": "gmail.com"
      +"qtdR": 526
    }
    2 => {#54262
      +"dominio": "hotmail.com"
      +"qtdR": 274
    }
    3 => {#54263
      +"dominio": "terra.com.br"
      +"qtdR": 1
    }
  ]
}

我想在没有有效计数的情况下获得值 0;

我想得到的结果:

Collection {#54236
  #items: array:4 [
    0 => {#54260
      +"dominio": "gmail.com"
      +"qtdR": 526
    }
    1 => {#54261
      +"dominio": "hotmail.com"
      +"qtdR": 274
    }
    2 => {#54262
      +"dominio": "outlook.com"
      +"qtdR": 0
    }
    3 => {#54263
      +"dominio": "bol.com.br"
      +"qtdR": 2
    }
    4 => {#54264
      +"dominio": "live.com"
      +"qtdR": 0
    }
    5 => {#54265
      +"dominio": "terra.com.br"
      +"qtdR": 1
    }
  ]
}

所以一直到数组的末尾,如上例,但我直到最后一个域才做,我认为可以理解预期的结果。

我用:

        ->table('producao_email')
        ->selectRaw('dominio,IFNULL(count(*),0) as qtdR')
        ->where('cod_cliente', $cliente_id)
        ->where('lote',$lote)
        ->where('cod_status','R')
        ->whereIn('dominio',$dominiosL)
        ->groupBy('dominio')
        ->get();

结果:

  #items: array:4 [
    0 => {#54260
      +"dominio": "bol.com.br"
      +"qtdR": 2
    }
    1 => {#54261
      +"dominio": "gmail.com"
      +"qtdR": 526
    }
    2 => {#54262
      +"dominio": "hotmail.com"
      +"qtdR": 274
    }
    3 => {#54263
      +"dominio": "terra.com.br"
      +"qtdR": 1
    }
  ]
}

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    我不知道你为什么要收集结果,而它已经是一个集合,但是,你可以使用IfNull mysql 表达式:

    $values=\DB::connection('mysql_scipg')
            ->table('producao_email')
            ->selectRaw('dominio,IFNULL(count(*),0) as qtdR')
            ->where('cod_cliente', $cliente_id)
            ->where('lote',$lote)
            ->where('cod_status','R')
            ->whereIn('dominio',$dominiosL)
            ->groupBy('dominio')
            ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 2011-12-19
      • 1970-01-01
      相关资源
      最近更新 更多