2014-06-06 35 views
0

使用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 ...

我不明白为什么,它让我疯狂了几个小时!此外,当我只做一个计数,结果是正确的。

任何想法?

提前:)

回答

2

最后,我已经实现了这个基本SQL查询

$this->db->query('SELECT 
       u.*, 
       x.total_store, 
       y.total_event 
      FROM 
      user u 

      LEFT OUTER JOIN (SELECT s.store_user_id, COUNT(s.store_user_id) AS total_store 
       FROM store s 

       GROUP BY s.store_user_id) x ON x.store_user_id = u.user_id 

      LEFT OUTER JOIN (SELECT e.event_user_id, COUNT(e.event_user_id) AS total_event 

      FROM event e 

       GROUP BY e.event_user_id) y ON y.event_user_id = u.user_id 
     '); 

希望这将帮助其他人

+0

查询此查询是否安全?是否有必要转义值?https://codeigniter.com/user_guide/database/queries.html#escaping-queries –

1

当你算非常感谢()你计算行数,而不是结果集中的不同值的数量。你说得对,这个数字正在倍增:每个用户存储事件组合的结果集中都有一行。

+0

感谢您的解释。你有一个想法,我怎么能得到结果集中的独特价值? – Amos

+0

谢谢你的帮助。 –

相关问题