我有以下选择
$repairs = DB::select(DB::raw('
select r.id repair_id, w.name, w.surname
from repairs r
join repair_worker rw on r.id = rw.repair_id
join workers w on w.id = rw.worker_id
where r.vehicle_id = ?
group by w.name, w.surname, r.id
'),[$vehicle->id]);
我试图将w.name
和w.surname
放入一个字段中,例如用逗号分隔。有一个函数string_agg(column, ',')
但我没有运气让它工作。我总是得到语法错误。
我的尝试:
$repairs = DB::select(DB::raw('
select r.id repair_id, string_agg(w.name, w.surname, ', ') workers
from repairs r
join repair_worker rw on r.id = rw.repair_id
join workers w on w.id = rw.worker_id
where r.vehicle_id = ?
group by r.id
'),[$vehicle->id]);
你会怎么做?
我正在使用最新的Postgresql 9 +
答案 0 :(得分:4)
使用||
运算符执行字符串连接,然后汇总此结果。
$repairs = DB::select(DB::raw("
select r.id repair_id, string_agg(w.name || ' ' || w.surname, ', ') workers
from repairs r
join repair_worker rw on r.id = rw.repair_id
join workers w on w.id = rw.worker_id
where r.vehicle_id = ?
group by r.id
"),[$vehicle->id]);
答案 1 :(得分:0)
试试这个吗?
$repairs = DB::select(DB::raw("
select r.id repair_id, string_agg(concat(w.name, ',',w.surname), ', ') workers
from repairs r
join repair_worker rw on r.id = rw.repair_id
join workers w on w.id = rw.worker_id
where r.vehicle_id = ?
group by r.id
"),[$vehicle->id]);