使用CodeIgniter和Active Record处理项目。Active Record - CodeIgniter:3个连接表上的多个COUNT
我遇到了一个查询问题: 我在我的数据库中有3个表,我不仅想加入,而且还要对他们中的2个进行计数。这些表分别与USER_ID,store_user_id,event_user_id田联
表1:用户 USER_ID
表2:商店 store_user_id
表3:事件 event_user_id
我试图要做的是:
1 - 获取来自用户的所有数据 2 - 统计店铺数w第i store_user_id = user_ID的(也可能是0) 3 - 事件计数与event_user_id = user_ID的数量(也可能是0)
我已经在我的功能做到了这一点:
$this->db->select('*');
$this->db->select('COUNT(s.store_user_id) as total_store', FALSE);
$this->db->select('COUNT(e.event_user_id) as total_event', FALSE);
$this->db->from('user u');
$this->db->join('store s', 's.store_user_id = u.user_id', 'left'); // this joins the user table to store table
$this->db->join('event e', 'e.event_user_id = u.user_id', 'left'); // this joins the user table to event table
$this->db->group_by('u.user_id');
$q = $this->db->get();
if ($q->num_rows()>0){
foreach ($q->result() as $rows) {
$data[] = $rows;
}
return $data;
}
麻烦的是当我在我的视图中显示total_store和total_event时,结果是相同的,我认为它们之间的数字相乘..
例如: 对于用户,我有3个事件en 4个商店,结果显示为total_event = total_store = 12 ...
我不明白为什么,它让我疯狂了几个小时!此外,当我只做一个计数,结果是正确的。
任何想法?
提前:)
查询此查询是否安全?是否有必要转义值?https://codeigniter.com/user_guide/database/queries.html#escaping-queries –