Skip to content
Advertisement

SQL Join with 3 tables?

I’m trying to build a database for a football website.

here is the diagram for that. enter image description here

I’m now trying to make the top scorers page, and I’ve already managed to query the top scorers with the correspondent amount of goals in desc order using this code:

enter image description here What I’m trying to do now, is add a 3rd column with the team (equipa in portuguese) of each top scorer, but I’m not understanding how i can do that because everytime i use one more column in the select query it shows an error. Every goal as a id of the player who scored it, and every player as the id of is team, is it possible to do that?

Advertisement

Answer

First, let’s switch this to standard join syntax.

Note that you should group by ID, not name, in case two players have the same name. Because the ID is unique it’s find to group by ID but select the name.

And you’re counting goals, not names.

Now we can add the third join. We also need to group by the team’s ID if we’re going to include it in the select list. As before you can select the team name because the ID is unique.

Finally, if you want to show every player even if they don’t have a goal, use a right join jogador.

And this makes more sense using from jogador. Then we can ensure all players appear even those with no goals and no team (if that’s what you want).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement