1

I'm trying to convert ruby query to sql here is what I got so far:

sql2 = "SELECT teams.* FROM teams, (SELECT sum(goals) FROM players WHERE team_id = team_id);"
connection.execute(sql2)

and this is what I'm trying to write:

  Team Load (0.6ms)  SELECT "teams".* FROM "teams"
   (0.5ms)  SELECT SUM("players"."goals") FROM "players" WHERE "players"."team_id" = $1  [["team_id", 1]]
   (0.5ms)  SELECT SUM("players"."goals") FROM "players" WHERE "players"."team_id" = $1  [["team_id", 2]]

the above was created with : Team.all.map {|t| puts "#{t.name} and #{t.players.sum(:goals)}"}

a simple loop trough players, getting team name and summing team.players.goals

Ideas would be appreciated

9
  • Is there any special reason to not use Active Record? Commented May 20, 2015 at 16:50
  • SELECT sum(goals) FROM players GROUP BY team_id would do the trick. Or, if you want exactly what stupid AR does: SELECT sum(goals) FROM players WHERE team_id IN (SELECT id FROM teams). Commented May 20, 2015 at 16:52
  • @BSeven The snippet on how AR does it, posted by OP, is a perfect answer on “why not to use AR.” Commented May 20, 2015 at 16:53
  • @mudasobwa - What do you mean by "The snipped"? What exactly is wrong with AR? Commented May 20, 2015 at 16:55
  • @BSeven typo: snippet. Anyway, AR does “N+1 select” aka “N+1 query.” Google for that. Commented May 20, 2015 at 16:57

1 Answer 1

1
SELECT sum(goals) FROM players GROUP BY team_id 

would do the trick. Or, if you want exactly what stupid AR does:

SELECT sum(goals) 
FROM players 
WHERE team_id IN (SELECT id FROM teams)

or, with a name of team to be returned as well:

SELECT teams.name, sum(players.goals) 
FROM players 
  JOIN teams ON (players.team_id = teams.id)
GROUP BY team_id 
Sign up to request clarification or add additional context in comments.

1 Comment

the name trows an error, and it would get players name. When I need the teams name, thats why I been selecting all teams. THANK you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.