我目前将行添加到一起的方法是这样的:
$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'];
但后来我看到了SUM(),我尝试了这个:
SELECT SUM(xp) FROM skills WHERE playerName='Undercover'
它有效,但我需要xp的所有值,所以我尝试添加%xp
,但它无法正常工作。
我如何使用Sum()函数添加所有行而不是使PHP变形?
答案 0 :(得分:3)
聚合函数(IE:SUM,MIN,MAX,COUNT等)不能跨列工作 - 它们根据分组(GROUP BY
)和过滤(特定列)处理特定列的值( JOIN
和/或WHERE
条款。
要在列之间添加值,您需要像对常规数学方程式一样添加它们:
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'
如果你有一个与玩家名相关联的记录,那么你可以使用聚合函数:
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'
答案 1 :(得分:1)
这取决于表数据,如果每个玩家是一个实体(行),那么就可以添加列:
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'
但是每个玩家有更多的行然后您还需要对行进行求和
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'
答案 2 :(得分:0)
SELECT SUM(`Attackxp`) + SUM(`Defencexp`) + ... AS `total_sum`
FROM skills
WHERE playerName='Undercover'