我有一个查询要从电路中获取练习列表:
SELECT *
FROM workouts
INNER JOIN circuits ON workouts.id = circuits.workout_id
INNER JOIN circuit_steps ON circuits.id = circuit_steps.circuit_id
INNER JOIN exercises ON exercises.id = circuit_steps.exercise_id
WHERE workouts.id = ${req.params.id}
当前结果是这样(为简洁起见,基本字段)
[
{
name: "Push Up",
circuit_id: 1
},
{
name: "Bicep Curl",
circuit_id: 1
},
{
name: "Squat",
circuit_id: 2
},
{
name: "Walk out",
circuit_id: 2
}
]
我希望能够GROUP
circuit_steps.circuit_id
的结果,所以结果是这样的:
[
[
{ name: 'Push Up', circuit_id: 1},
{ name: 'Bicep Curl', circuit_id: 1},
],
[
{ name: 'Squat', circuit_id: 2},
{ name: 'Walk Out', circuit_id: 2},
],
]
答案 0 :(得分:0)
您可以使用string_agg()
:
SELECT cs.circuit_id, string_agg(e.name, ',') as execise_names
FROM workouts w INNER JOIN
circuits c
ON w.id = c.workout_id INNER JOIN
circuit_steps cs
ON c.id = cs.circuit_id INNER JOIN
exercises e
ON e.id = cs.exercise_id
WHERE workouts.id=${req.params.id}
GROUP BY cs.circuit_id