【发布时间】:2018-07-19 22:12:35
【问题描述】:
我有 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);
当我对 unit_count 进行 group_concat 时,只有那些属性和单位会在 unit 存在的地方连接。
例如上面的查询返回如下结果:
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
【问题讨论】:
-
group_concat,有一个最大限制,通常比你所说的要多得多。
-
最大长度?我已通过以下方式更改了默认值: DB::statement('SET SESSION group_concat_max_len = 10485760');
-
查询构建器太垃圾了,您的查询太碎了,我无法真正查看它,对不起,限制只是我对这类问题的看法。我建议在Mysql中尝试查询,通过PHPmyadmin,先告诉你得到你想要的。
-
@ArtisticPhoenix 我已经用我的 sql 原始查询更新了它
-
我不完全确定您的预期结果或数据是什么,但在
... p.pty_name,'|',coalesce(cntunits,0)) as pty_details, ...中添加coalesce有帮助吗?我假设您左连接中的coalesce可能不会像您认为的那样做。
标签: php mysql laravel laravel-query-builder