1

I own an rpg and want to add up all the levels of the users monster and get an end number.

So I narrowed it down for one user and works great.

$_SESSION['username'] = "smbisme";


$query = "SELECT belongsto, SUM(level) FROM user_pokemon WHERE `belongsto` = '".$_SESSION['username']."' "; 

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
    echo $row['belongsto'];
    echo "". $row['SUM(level)'];
    echo "<br />";
}

Now, that shows and works for the user 'smbisme' but now I want to do it for all users.

So I try and take the where out like so.

$query = "SELECT belongsto, SUM(level) FROM user_pokemon  "; 

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
    echo $row['belongsto'];
    echo "". $row['SUM(level)'];
    echo "<br />";
}

But then for some reason i am only getting the highest result ( 1 result ) i would like to do what i did for the 1 user but grab all of the results instead of just the one user.

4

2 回答 2

1

You need to use a group by statement for multiple row aggregates:

SELECT 
    belongsto, 
    SUM(level) 
FROM 
    user_pokemon 
group by 
    belongsto

On that note, as PLB points out in the comments, this code is rather vunlerable to a code injection. You should consider using a prepared statement instead to get this result. No injections, it's a good thing.

To order by a column or aggregate:

SELECT 
    belongsto, 
    SUM(level) as sumLevel 
FROM 
    user_pokemon 
group by 
    belongsto 
order by 
    sumLevel desc
于 2012-09-13T12:39:18.320 回答
1

SUM is an aggregate function so you need a group by

SELECT belongsto, SUM(level) as sumlevel FROM user_pokemon group by belongsto order by sumlevel DESC
于 2012-09-13T12:39:32.470 回答