Tuesday, March 7, 2017

MYSQL QUERY multiple tables count

I am having problems building a query which delimit the number of lawyers by branch of law in one particular territory(province) of the country.

I have four tables, one with the branchlaws, one for users, one where lawyers add branches where the practice law and one for territories.

I am able to summarize all this information with the following query:

 $lawyersbyprovince = DB::table('branchlawsubareas')

            ->leftJoin('lawyerbranches', function($join)
        {

            $join->on( 'branchlawsubareas.id', '=', 'lawyerbranches.subarea_id');
        })

            ->leftJoin('users', function($join) 
        {
            $join->on( 'lawyerbranches.user_id', '=', 'users.id');
        })
            ->leftJoin('states', function($join)
        {
            $join->on( 'users.working_province', '=', 'states.id_state');
        })

            ->leftJoin('branchlaws', 'branchlawsubareas.area_id', '=', 'branchlaws.id')
            ->select('branchlawsubareas.name as subarea',


             DB::raw('count(lawyerbranches.subarea_id) as total')


             ,'branchlawsubareas.id' )
            ->where('states.id_state','=', $province)

            ->groupBy('branchlawsubareas.id')

            ->get();

This query returns the number of lawyers per branch of law but it does not delimit by province. I have spent enough time trying things but obviously I missing something.

Any help will be much appreciated.



via lostintheriver

Advertisement