查询构造器(DB:Table)的聚合函数:
count():统计符合条件的记录数
max(column):某列的最大值
min(column):某列的最小值
avg(column):某列的平均值
聚合函数!
查询构造器中的聚合函数
聚合函数使用
查询构造器的使用
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use phpDocumentor\Reflection\DocBlock\Tags\Var_; class StudentController extends Controller { public function test1() { // $students = DB::select('select * from student'); // var_dump($students); //新增 // $bool = DB::insert('insert into student(name,age) values(?,?)', ['hanmeimei', 17]); // var_dump($bool); //修改 // $num = DB::update('update student set age=? where name=?',[20, 'lee']); // var_dump($num); //查询 $students = DB::select('select * from student where id>?', [1002]); dd($students); } //查询构造器增加数据 public function query1() { //查询控制器 // $bool = DB::table('student')->insert(['name' => 'mac', 'age' => 23]); // var_dump($bool); // $num = DB::table('student')->insertGetId(['name'=>'cai', 'age'=>22]); // var_dump($num); $bool = DB::table('student')->insert([ ['name' => 'nam1', 'age' => 24], ['name' => 'name2', 'age' => 25] ]); var_dump($bool); } //查询构造器更新数据 public function query2() { // $num = DB::table('student')->where(['id' => 1001])->update(['name' => 'coco', 'age' => 30]); // var_dump($num); //全表age+3 自增 // $num = DB::table('student')->increment('age',3); // var_dump($num); //全表age-3 自减 $num = DB::table('student')->decrement('age', 3); var_dump($num); } //查询构造器删除数据 public function query3() { $num = DB::table('student')->where('id', 15)->delete(); var_dump($num); // $num = DB::table('student')->where('id','>=',13)->delete(); // var_dump($num); //一键清空数据 // DB::table('student')->truncate(); } public function query4() { //get() // $students = DB::table('student')->get(); // var_dump($students); //first() // $student = DB::table('student')->orderBy('id','desc')->first(); // dd($student); //where() // $students = DB::table('student')->where('id','>=',1002)->get(); // dd($students); //where()多条件 // $students = DB::table('student')->whereRaw('id >= ? and age >= ?', [1001, '25'])->get(); // dd($students); //pluck // $names = DB::table('student')->pluck('name'); // dd($names); //select // $students = DB::table('student')->select('id','name','age')->get(); // dd($students); //chunk(定义一次查几条数据) echo '<pre>'; DB::table('student')->orderBy('id')->chunk(1000, function ($students) { var_dump($students); }); } //聚合函数 public function query5() { //count() // $num = DB::table('student')->count(); // var_dump($num); //max() // $max = DB::table('student')->max('age'); // var_dump($max); //min() // $min = DB::table('student')->min('age'); // var_dump($min); //avg() // $avg = DB::table('student')->avg('age'); // var_dump($avg); //sum() $num = DB::table('student')->sum('age'); var_dump($num); } }
查询构造器中的聚合函数
count() max() min() avg() sum()
DB::table('student')->count(); //总条数
DB::table('student')->max('age'); //最大值
DB::table('student')->min('age'); //最小值
DB::table('student')->avg('age'); //平均值
DB::table('student')->sum('age'); //总和