V
V
vetsmen2020-07-01 14:34:07
MySQL
vetsmen, 2020-07-01 14:34:07

How to write a query with joins?

Good afternoon.
There is a Users table in relation to other tables (Run, Ride, Swim, etc)
The task is to pull out all Users with one query and attach the sum of kilometers from tables with relationships to each user.
But the query below does not work with all of them together, because with each selection of rows it becomes more and more
How can I solve this problem?

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"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2020-07-01
@freeExec

You need to group before join. Use FROM SELECT.
And so it turns out that in run and ride one line each and everything is fine (you got 1 line), but in swim it will give 5 lines. But in these four lines for run and ride there will be not zeros, but some random value from their previous lines, so your sums do not match.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question