如何从MySQL表中的两个不同列中获取总和

时间:2017-03-20 13:40:03

标签: mysql sql

我在名为“match_scores”的表格中有以下列:

echo '<pre>';
var_dump($_FILES);
echo '</pre>';

我希望结果是:

<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" id="sell-images" name="images[]" multiple>

    <input type="submit" value="submit">
</form>

3 个答案:

答案 0 :(得分:4)

你可以&#34; univot&#34;数据然后重新聚合。在SQL中,这看起来像:

select player, sum(points) as points
from ((select player_1 as player, player_1_points as points from match_scores ms1) union all
      (select player_2 as player, player_2_points as points from match_scores ms2) 
     ) t
group by player;

这将数据作为包含两列的结果集返回。您可以在SQL中转换为字符串,但我真的建议您在应用程序层执行此操作。

答案 1 :(得分:1)

这是解决问题的查询:

SELECT DISTINCT (player), sum(points)
FROM (
       SELECT player_1 AS player, player_1_points AS points FROM match_scores
       UNION ALL 
       SELECT player_2 AS player, player_2_points AS points FROM match_scores
     ) AS t
GROUP BY player

所以你注意到的别名放置在最后,只有一个。由于某种原因,在每个选择结尾处放置别名仍然会导致错误

答案 2 :(得分:0)

这应该有用..

select player, sum(points) as points
from (select player_1 as player, player_1_points as points 
      from match_scores 
      union all
      select player_2 as player, player_2_points as points 
      from match_scores) as a
group by player;