GROUP_CONCAT 给出了错误的值

GROUP_CONCAT gives incorrect values

我有 3 个 table:用户、属性、单位
用户table:

user_id   user_name

属性table

pty_id   pty_name   user   pty_status

单位Table

unit_id   unit_name  pty_id  unit_status

我想显示用户详细信息、属性和单位数量及其详细信息。 这是我的查询:

   DB::statement('SET SESSION group_concat_max_len = 10485760');

      $ar = DB::table('users as u')
         ->leftjoin('properties as p', function($join)  {
                   $join->on('p.user_id', '=', 'u.user_id')->where('p.pty_status', '!=' ,0 ); 
                  })

         ->leftJoin(
                 DB::raw("
                  (select COALESCE(count(unit_id),0) AS cntunits, pty_id as temp_pty
                  from  property_units as pu3 
                  left join properties as p2 on pu3.unit_pty_id = p2.pty_id
                  where pu3.unit_status!=0  
                  group by p2.pty_id) as temp"), 'p.pty_id', '=', 'temp.temp_pty')

          ->select(
      DB::raw("group_concat(DISTINCT CONCAT(ej_p.pty_id,'|',ej_p.pty_name,'|',cntunits)) as pty_details"), 
      DB::raw("group_concat(DISTINCT CONCAT(ej_p.pty_id,'|',ej_p.pty_name)) as pty_details_copy")
    )->paginate(10);

当我 group_concat unit_count 时,只有那些属性和单位在单位存在的地方连接起来。

例如上面的查询returns结果如下:

 pty_details              pty_details_copy
  7|I2|2       7|I2, 22|tR ,51|SG APARTMENT,54_||_GA APARTMENTS,

为什么带单位的属性(其中单位计数=0)不具有约束力?我哪里出错了?

编辑

这是原始查询:

select group_concat(DISTINCT CONCAT(p.pty_id,'|',p.pty_name,'|',cntunits)) as pty_details, 
     group_concat(DISTINCT CONCAT(p.pty_id,'|',p.pty_name)) as pty_details_copy
     from users as  u
     left join properties as p on p.user_id = u.user_id and p.pty_status !=0
     left join 
     (select COALESCE(count(unit_id),0) AS cntunits, pty_id as temp_pty
                  from  property_units as pu3 
                  left join properties as p2 on pu3.unit_pty_id = p2.pty_id
                  where pu3.unit_status!=0  
                  group by p2.pty_id) as temp on p.pty_id = temp.temp_pty

您第一次加入的 WHERE 应该是 ON 的一部分。

正如 Solarflare 所建议的,当我像这样更改查询时得到了所需的结果:

  $ar = DB::table('users as u')
     ->leftjoin('properties as p', function($join)  {
               $join->on('p.user_id', '=', 'u.user_id')->where('p.pty_status', '!=' ,0 ); 
              })

     ->leftJoin(
             DB::raw("
              (select COALESCE(count(unit_id),0) AS cntunits, pty_id as temp_pty
              from  property_units as pu3 
              left join properties as p2 on pu3.unit_pty_id = p2.pty_id
              where pu3.unit_status!=0  
              group by p2.pty_id) as temp"), 'p.pty_id', '=', 'temp.temp_pty')

      ->select(
  DB::raw("group_concat(DISTINCT CONCAT(ej_p.pty_id,'|',ej_p.pty_name,'|',coalesce(cntunits, 0))) as pty_details"))->paginate(10);