I am trying to create a simple player profile website and am running into a problem with my SQL.
I have a player table and a previous clubs table. As this is a many-to-many relationship, I am using a look up table (player previous clubs) between the player and previous clubs table.
This all seemed to be working fine until I ran my sql which looks like this:
SELECT player.id, player.name AS name, age, position, height, weight, previousclubs.name AS previousclubs, satscore, gpa
FROM player
INNER JOIN playerpreviousclubs
ON player.id = playerid
INNER JOIN previousclubs
ON previousclubid = previousclubs.id
The problem is that if a player has more then one previous club, then all of the information (apart from the previous club) is duplicated so I end up with something like this.
RESULT SET 1
Name: John Smith
Age: 23
Previous Clubs: Arsenal
RESULT SET 2
Name: John Smith
Age: 23
Previous Clubs: Reading
What I would like it to do is the following:
RESULT SET 1
Name: John Smith
Age: 23
Previous Clubs: Arsenal, Reading
Can anyone explain to me why this is currently happening please and how I go about rectifying it.
Thanks
You have to use GROUP BY combined with aggregate function in order to achieve wished behaviour (i.e. you need to “aggregate” n-tuples retrieved from DB, that’s why the functions are called aggregate :-)). Choice of aggregate function depends on RDBMS you are using, for example:
MySQL:
PostgreSQL (v8.4 and higher):