My current method to add the rows toge开发者_开发百科ther is like so:
$totalxp = $row['Attackxp'] + $row['Defencexp'] + $row['Strengthxp'] + $row['Hitpointsxp'] + $row['Rangedxp'] + $row['Prayerxp'] + $row['Magicxp'] + $row['Cookingxp'] + $row['Woodcuttingxp'] + $row['Fletchingxp'] + $row['Fishingxp'] + $row['Firemakingxp'] + $row['Craftingxp'] + $row['Smithingxp'] + $row['Miningxp'] + $row['Herblorexp'] + $row['Agilityxp'] + $row['Thievingxp'] + $row['Slayerxp'] + $row['Farmingxp'] + $row['Runecraftxp'] + $row['Constructionxp'];
But then I saw SUM() and I tried this:
SELECT SUM(xp) FROM skills WHERE playerName='Undercover'
It works but I needed all the values of xp, so I tried adding %xp
but it wont work.
How could I use the Sum() function to add all the rows up instead of straining PHP?
Aggregate functions (IE: SUM, MIN, MAX, COUNT, etc) don't work across columns--they work on the values for the specific column, based on the grouping (GROUP BY
) and filteration (JOIN
and/or WHERE
clause).
To add up values across columns, you need to add them like you would for normal mathematical equations:
SELECT Attackxp + Defencexp + Strengthxp + Hitpointsxp + Rangedxp + Prayerxp + Magicxp + Cookingxp+ Woodcuttingxp + Fletchingxp + Fishingxp + Firemakingxp + Craftingxp + Smithingxp + Miningxp + Herblorexp + Agilityxp + Thievingxp + Slayerxp + Farmingxp + Runecraftxp + Constructionxp AS total_xp
FROM skills
WHERE playerName = 'Undercover'
If you have more than one record associated to a playername, then you can use an aggregate function:
SELECT SUM(Attackxp + Defencexp + Strengthxp + Hitpointsxp + Rangedxp + Prayerxp + Magicxp + Cookingxp+ Woodcuttingxp + Fletchingxp + Fishingxp + Firemakingxp + Craftingxp + Smithingxp + Miningxp + Herblorexp + Agilityxp + Thievingxp + Slayerxp + Farmingxp + Runecraftxp + Constructionxp) AS total_xp
FROM skills
WHERE playerName = 'Undercover'
That depend of the table data if each player is one entity (row) then is enaught to add columns:
SELECT Attackxp + Defencexp + Strengthxp + Hitpointsxp +Rangedxp + Prayerxp + Magicxp + Cookingxp + Woodcuttingxp + Fletchingxp + Fishingxp + Firemakingxp + Craftingxp + Smithingxp + Miningxp + Herblorexp + Agilityxp + Thievingxp + Slayerxp + Farmingxp + Runecraftxp + Constructionxp
As totalSkills FROM skills WHERE playerName = 'Undercover'
But is there more rows per player then You will need to sum also the rows
SELECT SUM(Attackxp + Defencexp + Strengthxp + Hitpointsxp +Rangedxp + Prayerxp + Magicxp + Cookingxp + Woodcuttingxp + Fletchingxp + Fishingxp + Firemakingxp + Craftingxp + Smithingxp + Miningxp + Herblorexp + Agilityxp + Thievingxp + Slayerxp + Farmingxp + Runecraftxp + Constructionxp)
As totalSkills FROM skills WHERE playerName = 'Undercover'
SELECT SUM(`Attackxp`) + SUM(`Defencexp`) + ... AS `total_sum`
FROM skills
WHERE playerName='Undercover'
精彩评论