【问题标题】:Laravel full join with groupby and countLaravel 完全加入 groupby 和 count
【发布时间】:2017-08-01 09:55:54
【问题描述】:

我正在尝试在 laravel 中获取 master child,使用 count(child) 和所有 master raw,使用 groupby。下面是表格记录和laravel代码。

父表

    +-------------+------------+  
    | Id          | Name       |
    +-------------+------------+  
    | 1           | a          |
    +-------------+------------+    
    | 2           | b          |
    +-------------+------------+ 
    | 3           | c          |
    +-------------+------------+

子表

    +-------------+------------+  
    | parent_Id   | Code       |
    +-------------+------------+
    | 1           | d1         |
    +-------------+------------+ 
    | 1           | d1         |
    +-------------+------------+    
    | 1           | d1         |
    +-------------+------------+ 
    | 1           | d1         |
    +-------------+------------+    
    | 2           | d2         |
    +-------------+------------+ 
    | 2           | d3         |
    +-------------+------------+ 

结果 计算孩子中所有相同的父ID并显示所有主ID,如果孩子的主ID不超过0。

    +-------------+----------------------+ 
    |countparentIds in child| parentName       
    +-------------+----------------------+ 
    | 6                     | a          |
    +-------------+----------------------+  
    | 2                     | b          |
    +-------------+----------------------+  
    | 0                     | c          |
    +-------------+----------------------+

现在我的 laravel 雄辩如下。

 $master = DB::table('parents')
        ->select(array('parent.name as Name', DB::raw('COUNT(child.parent_id) as countparentids')))
        ->join('child', 'parent.id', '=', 'child.parent_id', 'left outer')
        ->where(child.code,'d1')
        ->orderBy('parent.name')
        ->groupBy('parent.id')
        ->groupBy('parent.name')
        ->get();

现在我得到了结果,父表的所有行,并计算具有父 ID 的子表。

【问题讨论】:

  • 你有什么问题?
  • 结果不显示所有父行,它显示子计数但不是所有父行,我正在寻找所有父名称 countofchild_parentid。
  • for instanc child table has code = d1, 所以结果应该是第一行 countparentids in child = 4 , parentname = a countparentids in child = 0 , parentname = b countparentid in child = 0 , parentname = c
  • 使用 leftJoin 代替 join

标签: php mysql laravel relational-database


【解决方案1】:

尝试CASE WHEN
像这样

   $ter = DB::table('parents')
    ->leftjoin('child', 'parent.id', '=', 'child.parent_id')
    ->select(array('parent.name as Name', DB::raw('CASE WHEN (child.code= "d1") THEN COUNT(child.parent_id) ELSE 0 END as countparentids')))
    ->orderBy('parent.name')
    ->groupBy('parent.name')
    ->get();

【讨论】:

  • 我的代码是 leftjoin join('table' ,'parent.column' ,'=',' 'childcol', 'left outer')。
  • 好的,你需要根据具体情况给出你的 where 条件
  • 你所说的情况是什么意思。
  • 当你写 ->where(child.code,'d1') 所以你没有得到想要的 o/p
  • 试试这个,看看你有没有得到你的 o/p
猜你喜欢
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 2022-10-12
  • 2012-06-24
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多