(Run, Ride, Swim, etc)
Стоит задача одним запросом вытащить всех Users и к каждому юзеру прикрепить сумму километров из таблиц с отношениями
Но запрос ниже не работает со всеми вместе, ибо с каждым джоином повторяющихся данных все больше и больше
Как можно решить эту проблему?
SELECT
"user"."id",
"user"."name",
SUM("run"."km") AS "run_km",
SUM("ride"."km") AS "ride_km",
SUM("swim"."km") AS "swim_km"
FROM "user"
LEFT JOIN "run"
ON "user"."id" = "run"."userId"
LEFT JOIN "ride"
ON "user"."id" = "ride"."userId"
LEFT JOIN "swim"
ON "user"."id" = "swim"."userId"
GROUP BY "user"."id»
SELECT "user"."id", "user"."name", "sum_run"."km" AS "run_km" FROM "user" LEFT JOIN (select "run"."userId", sum("run"."km") AS "km" from "run" group by "run"."userId" ) AS "sum_run" ON "user"."id" = "sum_run"."userId" с другими таблицами аналогично поступить
Или же использовать "каскад" группировок: WITH user_runs AS ( SELECT "user".id, "user".name, SUM(run.km) AS run_km FROM "user" LEFT JOIN run ON "user".id = run.userId GROUP BY "user".id ), user_runs_rides AS ( SELECT user_runs.id, user_runs.name, user_runs.run_km, SUM(ride.km) AS ride_km FROM user_runs LEFT JOIN ride ON ride.userId = user_runs.id GROUP BY user_runs.id, user_runs.name, user_runs.run_km ), ... Или просто подзапросы: SELECT "user".id, "user".name, (SELECT SUM(run.km) FROM run WHERE run.userId = "user".id) AS run_km, (SELECT SUM(ride.km) FROM ride WHERE ride.userId = "user".id) AS ride_km, ... FROM "user"
Обсуждают сегодня