为什么这个查询不是显示每个用户的点总和,而是显示所有在一起的总和
我编写了一个SQL
查询,显示所有用户的所有点的总和,而我希望:显示每个用户的点数总和。
我写的表包含以下内容:
id | Score
1 | 20
2 | 30
2 | 50
1 | 10
总表:
id | points
1 | 30
1 | 40
我想要的是添加user(1) = 30
和user(2) = 80
Id: 1 = 30 = Fail
Id: 2 = 80 = Pass
我写的查询:
$query = "SELECT SUM(sg.score) as sum, SUM(a.total) as suma FROM points as sg, totalpoints as a
WHERE a.id = 1 GROUP BY sg.id";
相关的PHP
代码如下:
<?php
foreach($rowsum as $rowsm):
if( ' '. htmlentities($rowsm['sum']) . '' > 50 )
echo 'Pass';
else if( ' '. htmlentities($rowsm['sum']) . '' >= 40 )
echo 'Failed';
echo ' ' . htmlentities($rowsm['sum'], ENT_QUOTES, 'UTF-8') . '<br>';
endforeach;
?>
答案 0 :(得分:1)
我想您应该期待使用GROUP BY
子句:
SELECT
SUM(score) AS sum
FROM
points
GROUP BY
id
ORDER BY
id
答案 1 :(得分:1)
您需要按用户ID进行分组:
SELECT SUM(score) as sum FROM points GROUP BY id ORDER BY id
您还有一个不正确的WHERE子句
WHERE id=id
不需要。
答案 2 :(得分:0)
您已省略GROUP BY子句:
$query = "SELECT SUM(score) as `sum` FROM points GROUP BY id ORDER BY id";
您的WHERE子句不是必需的。
答案 3 :(得分:0)
您需要按照以下方式进行分组,它会为您提供每个用户的分数总和
SELECT SUM(score) as sum FROM points
group by id
ORDER BY id
如果您需要为特定用户找到它,只需将where条件添加为
SELECT SUM(score) as sum FROM points
where id = 1
以上将给出id = 1的分数总和,并可根据需要更改其他值。