[英]codeigniter need help grouping and sum of tables
Here is my situation. 这是我的情况。 I have 2 tables. 我有2张桌子。 I am trying to combine the 2 tables, which I have been successful with join. 我正在尝试合并2个表,这些表在join方面已经取得了成功。 Now I need to add up the values, but I don't want to repeat the same user when I display. 现在,我需要将这些值加起来,但是我不想在显示时重复相同的用户。
Example tables: 表格示例:
Table 1: 表格1:
users
[ id ][name ]
[ 1 ][John Doe]
[ 2 ][Jane Doe]
[ 3 ][Joe Doe]
Table 2: 表2:
activity_hours
[ id ][user_id][hours]
[ 1 ][ 1 ][ 3 ]
[ 1 ][ 2 ][ 1 ]
[ 1 ][ 3 ][ 4 ]
[ 1 ][ 1 ][ 2 ]
[ 1 ][ 2 ][ 3 ]
I want to add up all the hours for each user from activity hours, but want to match the amount to there name 我想将每个用户的所有小时数与活动时间相加,但要将金额与该名称相匹配
Here is my current code: Hours_model.php 这是我当前的代码: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 hours_veiw.php
foreach ($result as $activity) {
echo $activity->name.' : '.$activity->hours;
}
Desired output: 所需的输出:
John Doe : 5
Jane Doe : 4
Joe Doe : 4
== UPDATE == ==更新==
Thank you user3774708. 谢谢user3774708。 That little bit that you provided I was able to solve the rest. 您提供的那一点我能够解决其余的问题。 Here is the rest of the code that I needed to change: I changed: 这是我需要更改的其余代码:我更改了:
activity_hours.hours
to 至
sum(activity_hours.hours) as hours
final database query 最终数据库查询
$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();
Use Group_by on users.id 在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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.