我有以下选择
$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+
最佳答案
使用 ||
运算符执行字符串连接,然后聚合此结果。
$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]);
关于php - String_agg 用于多列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43687600/