【问题标题】:Laravel 5.6 query builder sumLaravel 5.6 查询构建器总和
【发布时间】:2019-01-09 17:45:43
【问题描述】:

我有 table 'peserta' 结构

  • 名称(varchar)
  • h1(整数)
  • h2(整数)
  • h3(整数)

我想选择 (h1 + h2 + h3) 作为总数并按限制 30 升序排列。什么是正确的查询生成器?

> $rank['rank'] = DB::table('peserta')->select('*', '(n1+n2+n3) as
> total')->limit(30)->orderBy('total', 'asc')->get();

【问题讨论】:

    标签: php mysql sql laravel phpmyadmin


    【解决方案1】:

    使用原始查询:

    DB::table('peserta')
       ->select(
            '*', 
           DB::raw('(n1+n2+n3) as > total')
        )
       ->limit(30)
       ->orderBy('total', 'asc')
       ->get();
    

    【讨论】:

      【解决方案2】:

      你可以用雄辩的 selectRaw 方法来做到这一点。

      $rank['rank'] = DB::table('peserta')
                      ->selectRaw('*, h1 + h2 + h3 as total')
                      ->limit(30)
                      ->orderBy('total', 'asc')
                      ->get();
      

      【讨论】:

        【解决方案3】:
        DB::table('peserta')
         ->select('*', DB::raw('(IFNULL(h1,0) + IFNULL(h2,0)) + IFNULL(h3,0) as total'))
         ->orderBy('total')
         ->limit(30)
         ->get();
        

        如果列值之一为空,我将设置为 0,否则如果 h1、h2 或 h3 之一为空,total 将为您提供空值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-01-29
          • 2016-12-26
          • 2021-09-25
          • 2021-10-22
          • 2018-11-01
          • 2020-03-19
          • 1970-01-01
          相关资源
          最近更新 更多