MySQL SUM,JOIN和GROUP BY ...正确的结构

时间:2013-09-18 17:20:07

标签: mysql sql laravel laravel-4

我在浏览表格时遇到了一些麻烦,并将我的SQL语句结构化为GROUP BY team_id(使用Laravel 4 Fluent)。如果我删除GROUP BY,我将获得每个用户的总步数。但我需要的是每个团队的总步骤。

SQL声明:

SELECT  `user_challenge`.`team_id` ,  `teams`.`name` , (
SELECT SUM( activities.steps ) 
FROM activities
WHERE activities.user_id = users.id
AND activities.created_at <=  '2013-11-30 15:32:45'
AND activities.date >=  '2013-10-01 15:32:45'
AND activities.date <=  '2013-11-30 15:32:45'
) AS steps
FROM  `user_challenge` 
INNER JOIN  `users` ON  `user_challenge`.`user_id` =  `users`.`id` 
INNER JOIN  `teams` ON  `user_challenge`.`team_id` =  `teams`.`id` 
WHERE  `user_challenge`.`challenge_id` =2
AND  `user_challenge`.`team_id` IS NOT NULL 
GROUP BY  `user_challenge`.`team_id`

PHP(Laravel)如果有帮助:

$subquery = "(SELECT SUM(activities.$type) FROM activities WHERE activities.user_id = users.id AND activities.created_at <= '". $challenge->end_date ."' AND activities.date >= '". $challenge->start_date ."' AND activities.date <= '". $challenge->end_date ."') as $type";
$teams = DB::table('user_challenge')
    ->where('user_challenge.challenge_id', $challenge->id)
    ->whereNotNull('user_challenge.team_id')
    ->join('users','user_challenge.user_id','=','users.id')
    ->join('teams','user_challenge.team_id','=','teams.id')
    ->select('user_challenge.team_id', 'teams.name',DB::raw($subquery))
    ->groupBy('user_challenge.team_id')
    ->get();

使用GROUP BY输出:

team_id, name, steps
1, Team 1, null

没有GROUP BY的输出:

team_id, name, steps
1, Team 1, null
1, Team 1, 13000
1, Team 1, 10000

期望输出:

team_id, name, steps
1, Team 1, 23000

tables

1 个答案:

答案 0 :(得分:1)

您应该在单个查询中使用group by而不是嵌套(您拥有它的方式)。 这是接近它的一种方法:

SELECT  `user_challenge`.`team_id` ,  `teams`.`name` , SUM(`userStepSum`) as `TeamStepSum`
FROM  `user_challenge` 
INNER JOIN  `users` ON  `user_challenge`.`user_id` =  `users`.`id` 
INNER JOIN  `teams` ON  `user_challenge`.`team_id` =  `teams`.`id` 
INNER JOIN 
(
SELECT activities.user_id, SUM( activities.steps ) as `userStepSum`
FROM activities
where 
AND activities.created_at <=  '2013-11-30 15:32:45'
AND activities.date >=  '2013-10-01 15:32:45'
AND activities.date <=  '2013-11-30 15:32:45'
GROUP BY `activities`.`user_id`
) `user_steps` on `user_steps`.`user_id` = `user_challenge`.`user_id`
WHERE  `user_challenge`.`challenge_id` =2
AND  `user_challenge`.`team_id` IS NOT NULL 
GROUP BY  `user_challenge`.`team_id`

您也可以直接加入活动。祝你好运。