我有3个表:用户,属性,单位
用户表:
user_id user_name
属性表
pty_id pty_name user pty_status
单位表
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时,只有那些属性和单位在单位存在的地方进行汇总。
例如,上面的查询返回以下结果:
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
答案 0 :(得分:1)
正如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);
答案 1 :(得分:0)
第一次加入的WHERE应该是ON的一部分。