Jump to content

[SOLVED] SUM help on a join


Mr Chris

Recommended Posts

Hi Guys,

 

Wondering if anyone can help me with this join query.  I use the below to get a players name for a football match from a players table.

 

Now this works Great:

 

SELECT player_stats.player_id, players.player_name, players.position, player_stats.goals
from player_stats 
INNER JOIN players ON players.player_id = player_stats.player_id
WHERE players.player_id=1

 

However, I now want to add up how many goals they have scored

 

goals.jpg

 

Now I’ve tried doing this:

 

SELECT player_stats.player_id, players.player_name, players.position, SUM( player_stats.goals )
FROM player_stats
INNER JOIN players ON players.player_id = player_stats.player_id
WHERE players.player_id =1

 

So the total goals for this player would be 23

 

But get told I’m matching illegal groups.  Can anyone help?

 

Thanks

 

Chris

 

Link to comment
https://forums.phpfreaks.com/topic/60542-solved-sum-help-on-a-join/
Share on other sites

Use LEFT JOIN instead of INNER JOIN..

 

$query = "SELECT player_stats.player_id, players.player_name, players.position, SUM( player_stats.goals ) "
	. "FROM player_stats "
	. "LEFT JOIN players ON players.player_id = player_stats.player_id "
	. "WHERE players.player_id = 1";
$result = mysql_fetch_assoc(mysql_query($query));
print $result['goals'];

Thanks,

 

But using that join i'm still getting the same error:

 

Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause

 

SELECT player_stats.player_id, players.player_name, players.position, SUM( player_stats.goals )
FROM player_stats
LEFT JOIN players ON players.player_id = player_stats.player_id
WHERE players.player_id = 1

 

Also tried it in PHP with your code and got a mysql_fetch_assoc() error?

 

Any other ideas?

 

Thanks

 

Chris

I forgot the alias

 

$query = "SELECT player_stats.player_id, players.player_name, players.position, SUM( player_stats.goals ) as total_goals "
	. "FROM player_stats "
	. "LEFT JOIN players ON players.player_id = player_stats.player_id "
	. "WHERE players.player_id = 1";
$result = mysql_fetch_assoc(mysql_query($query));
print $result['total_goals'];

 

Hope it work!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.