I am trying to use two GROUP_CONCATs in the same SQL statement.
I have the following code:
try
{
$sql = 'SELECT player.id, player.name AS name, GROUP_CONCAT(previousclubs.name)
previousclubs, satscore, gpa, GROUP_CONCAT(link) link
FROM player INNER JOIN playerpreviousclubs
ON player.id = playerid
INNER JOIN previousclubs
ON previousclubid = previousclubs.id
INNER JOIN links
ON links.playerid = player.id
GROUP BY player.id';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching details: ' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row)
{
$names[] = array(
'id' => $row['id'],
'name' => $row['name'],
'previousclubs' => $row['previousclubs'],
'links' => $row['link']
);
}
include 'profiles.html.php';
If a player has say three previous clubs and one link, then instead of displaying like this:
Name: John Smith
Previous Clubs: Arsenal, Reading, QPR
Links: http://www.bbc.co.uk
IT DISPLAYS LIKE THIS:
Name: John Smith
Previous Clubs: Arsenal, Reading, QPR
Links: http://www.bbc.co.uk, http://www.bbc.co.uk, http://www.bbc.co.uk
WORSE STILL IF YOU HAVE MULTIPLE LINKS (TWO LINKS ARE USED BELOW) YOU GET THIS:
Name: John Smith
Previous Clubs: Arsenal, Arsenal, Reading, Reading, QPR, QPR
Links: http://www.bbc.co.uk, http://www.football.com, http://www.bbc.co.uk, http://www.football.com, http://www.bbc.co.uk, http://www.football.com
Can someone please provide some guidance on what is going on here and how to rectify it.
The first GROUP_CONCAT on previousclubs works fine by itself but when the second GROUP_CONCAT for links is thrown in the mix, the issues mentioned above are occuring.
Thanks for your time and help.
The problem is not GROUP_CONCAT, it is the arguments.
Your second group concat should be:
You can also control the ordering (in case you want most recent first, for instance). Check out the help page at http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat.