codeigniter需要帮助分组和表的总和

时间:2016-04-19 14:38:04

标签: php codeigniter join group-by sum

这是我的情况。我有2张桌子。我正在尝试将两个表合并,我已成功加入。现在我需要添加值,但我不希望在显示时重复相同的用户。

示例表:

表1:

users
[ id ][name    ]
[  1 ][John Doe]
[  2 ][Jane Doe]
[  3 ][Joe  Doe]

表2:

activity_hours
[ id ][user_id][hours]
[  1 ][  1    ][  3  ]
[  1 ][  2    ][  1  ]
[  1 ][  3    ][  4  ]
[  1 ][  1    ][  2  ]
[  1 ][  2    ][  3  ]

我想在活动时间内为每位用户添加所有小时数,但希望将金额与该名称相匹配

这是我目前的代码: Hours_model.php

    $this->db->select('
        users.id as id,
        users.name,
        activity_hours.hours
    ');

    $this->db->from('users');
    $this->db->join('activity_hours', 'users.id = activity_hours.user_id');

    $query = $this->db->get();
    return $query->result();

hours_veiw.php

foreach ($result as $activity) {
  echo $activity->name.' : '.$activity->hours;
}

期望的输出:

John Doe : 5
Jane Doe : 4
Joe Doe  : 4

== UPDATE ==

谢谢user3774708。你提供的那一点我能够解决剩下的问题。 以下是我需要更改的其余代码: 我改变了:

activity_hours.hours

sum(activity_hours.hours) as hours

最终数据库查询

$this->db->select('
    users.id as id,
    users.name,
    sum(activity_hours.hours) as hours
');

$this->db->from('users');
$this->db->join('activity_hours', 'users.id = activity_hours.user_id');
$this->db->group_by('users.id');
$query = $this->db->get();
return $query->result();

1 个答案:

答案 0 :(得分:2)

在users.id上使用Group_by

$this->db->select('
    users.id as id,
    users.name,
    activity_hours.hours
');

$this->db->from('users');
$this->db->join('activity_hours', 'users.id = activity_hours.user_id');
$this->db->group_by('users.id');
$query = $this->db->get();
return $query->result();