【问题标题】:How can I write Left Join Clause [duplicate]我该如何编写左连接子句[重复]
【发布时间】:2017-08-22 10:52:35
【问题描述】:

我有如下的 MySQL 查询

   SELECT AVG(COALESCE(ratings.rating_for_manager, 0)), consultants.id 
   FROM consultants
   LEFT JOIN ratings ON ratings.consultant_id = consultants.id
   GROUP BY  consultants.id

如何在 laravel Left Join 子句中编写上面的 MySQL 连接查询?

【问题讨论】:

    标签: mysql laravel laravel-5 left-join


    【解决方案1】:

    你可以使用leftJoin:

    DB::table('consultants')
        ->selectRaw('AVG(COALESCE(ratings.rating_for_manager, 0)), consultants.id ')
        ->leftJoin('ratings', 'ratings.consultant_id', 'consultants.id')
        ->groupBy('consultants.id')
        ->get();
    

    https://laravel.com/docs/5.4/queries#joins

    希望这会有所帮助!

    【讨论】:

    • 成功了,谢谢兄弟。
    • @Manjunath 很高兴我能帮上忙!
    • 好的,我一定会这样做的,再次感谢。
    【解决方案2】:
    $data = DB::table('consultants')
     ->leftJoin('ratings','consultants.id','=','ratings.consultant_id')
    ->groupBy('consultant.id')->get();
    

    【讨论】:

    • 添加一些关于为什么以及如何解决问题的解释将对提出问题的人有很大帮助。就目前而言,它可能是正确的答案,也可能不是,但对理解原因没有多大帮助。
    【解决方案3】:

    你应该试试这个:

    $rslt = DB::table('consultants')
        ->leftJoin('ratings','consultants.id','=','ratings.consultant_id')
        ->select('consultants.id',DB::raw('ifnull(AVG(ratings.rating_for_manager),0) as ratingsDetails'))
             ->groupBy('consultants.id')
             ->get();
    

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      相关资源
      最近更新 更多