【问题标题】:Get Count in mysql query in laravel在laravel的mysql查询中获取计数
【发布时间】:2016-01-14 10:15:14
【问题描述】:

我想选择每个项目的投票数。以下查询工作正常,但如果没有对某个项目投票,则该项目不会显示在结果中。我实际上想要每个项目的详细信息和投票。如果没有对项目的投票,则应显示计数为零。 我怎样才能实现它?

DB::table('wonders')
        ->leftjoin('vote','votes.wonderId','=','wonders.id')
        ->select('wonders.id','wonders.title',DB::raw('count(votes.vote) as votes'))
        ->get();

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    试试这个

    DB::table('wonders')
                ->leftjoin('vote','votes.wonderId','=','wonders.id')
                ->select('wonders.id','wonders.title',DB::raw('ifnull(count(votes.vote),0) as votes'))
                ->groupBy('wonders.id')
                ->get();
    

    【讨论】:

      【解决方案2】:

      也许你需要使用iffnull,试试这个

      DB::table('wonders')
              ->leftjoin('vote','votes.wonderId','=','wonders.id')
              ->select('wonders.id','wonders.title',DB::raw('ifnull(count(votes.vote),0) as votes'))
              ->get();
      

      【讨论】:

      • 没有效果相同的结果得到。它只返回具有至少 1 票的项目
      【解决方案3】:

      试试这个

      DB::table('wonders')
          ->leftjoin('vote','votes.wonderId','=','wonders.id')
          ->selectRaw('wonders.id','wonders.title',count(votes.vote) as votes)
          ->groupBy('wonders.id')
          ->get();
      

      【讨论】:

        猜你喜欢
        • 2013-04-02
        • 1970-01-01
        • 2015-02-04
        • 2021-09-25
        • 2014-11-13
        • 1970-01-01
        • 2018-01-13
        • 2016-11-10
        • 2012-10-20
        相关资源
        最近更新 更多