代码之家  ›  专栏  ›  技术社区  ›  Kyle

如何使用sum()对结果数组求和?

  •  0
  • Kyle  · 技术社区  · 15 年前

    我当前将行添加到一起的方法如下:

    $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?

    3 回复  |  直到 15 年前
        1
  •  3
  •   OMG Ponies    15 年前

    聚合函数(例如: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' 
    

    如果有多个记录与一个playername关联, 然后 您可以使用聚合函数:

    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'
    
        2
  •  1
  •   Damian Leszczyński - Vash    15 年前

    这取决于表数据,如果每个播放器是一个实体(行),则需要添加列:

    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'
    
        3
  •  0
  •   zerkms    15 年前
    SELECT SUM(`Attackxp`) + SUM(`Defencexp`) + ... AS `total_sum`
      FROM skills
     WHERE playerName='Undercover'