Laravel: Use only one statement, how to find out a table, different conditions corresponding data bar number
As the following table:
id name age sex 1 a 1 02 b 10 1 3 c 2 1
The number of sex is 1 and age is 2, sex is 1 and age is 5, sex is 1 and age is 10
Requirements: High efficiency
Maybe what I'm saying is not very clear, I need to figure out how many are 2 years old, how many are 5 years old, how many are 10 years old and three answers for sex is 1.
Note: It is best to laravel frame statements, preferably not the original ecological statement, the amount of data has hundreds of thousands of to millions of
All the big guys help
Reply content:
Laravel: Use only one statement, how to find out a table, different conditions corresponding data bar number
As the following table:
id name age sex 1 a 1 02 b 10 1 3 c 2 1
The number of sex is 1 and age is 2, sex is 1 and age is 5, sex is 1 and age is 10
Requirements: High efficiency
Maybe what I'm saying is not very clear, I need to figure out how many are 2 years old, how many are 5 years old, how many are 10 years old and three answers for sex is 1.
Note: It is best to laravel frame statements, preferably not the original ecological statement, the amount of data has hundreds of thousands of to millions of
All the big guys help
Try this sentence.
Table::select(DB::raw('age,count(id) count'))->where('sex',1)->groupBy('age')->get()->toArray();
SQL is not very understanding, but with Query Builder instead of eloquent ORM can improve efficiency, this ORM, although very powerful, but also laravel the slowest place.
If the main requirement is to use the aggregation function of DB
DB::table('yourtable')->where('sex', 1)->where('age', $age)->count();
I don't know if it's the main logic of the building.