Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 提取按管理员分组的组的成员和管理员的分数总和_Php_Mysql_Sql_Group By - Fatal编程技术网

Php 提取按管理员分组的组的成员和管理员的分数总和

Php 提取按管理员分组的组的成员和管理员的分数总和,php,mysql,sql,group-by,Php,Mysql,Sql,Group By,我有两个表:分数和用户: user: -------------- id | name | parent -------------- 1 | jack |0 -------------- 2 | John |1 -------------- 3 | Jim |1 -------------- 4 | Sara |0 -------------- 5 | Ann |4 -------------- 6 | Suzi |4 score: -------------------

我有两个表:分数和用户:

user:
--------------
id | name | parent
--------------
1  | jack |0
--------------
2  | John |1
--------------
3  | Jim  |1
--------------
4  | Sara |0
--------------
5  | Ann  |4
--------------
6  | Suzi |4



score:
------------------------
id | title_id | user_id | score
------------------------
1  | 2        |0        |5
------------------------
2  | 4        |1        |4
------------------------
3  | 5        |1        |4
------------------------   
家长是一个组的管理员,我想提取每个组的分数总和。现在我有这个:

select sum(score) from score left join user on user.id=score.user_id where title_id=2 and parent!=0 group by parent_id

但是这个返回的只是组成员的和,而不是组成员的和。有更好的查询吗?

我认为下面的查询符合您的要求。它使用案例来区分组长和成员,因此包括组长在内的所有成员:

select (case when u.parent_id = 0 then u.id else u.parent_id end) as grp, sum(s.score)
from user u left join
     score s
     on u.id = s.user_id and s.title_id = 2 
group by (case when u.parent_id = 0 then u.id else u.parent_id end);