简体   繁体   English

Laravel 5.6查询生成器总和

[英]Laravel 5.6 query builder sum

I have table 'peserta' with structure 我有带有结构的表“ peserta”

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

I want select (h1 + h2 + h3) as total and order by ascending with limit 30. what the right query builder? 我想选择(h1 + h2 + h3)作为总数,并通过限制30升序进行选择。什么是正确的查询构建器?

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

Use Raw query: 使用原始查询:

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

You can do this with eloquent selectRaw method. 您可以使用雄辩的selectRaw方法执行此操作。

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

I am setting 0 if one of the column value is null otherwise total will be giving you null value if one of h1,h2 or h3 is null. 如果列值之一为null,我将设置为0,否则,如果h1,h2或h3之一为null,total将为您提供null值。

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

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