2014-10-31 36 views
-2

複雜查詢我有2個表:笨:2個表

events  event_follows 
------- ------------- 
id   id 
title  user_id 
content event_id 
user_id 

我需要得到一定的USER_ID,事件的計數的所有事件,得到其隨後該用戶的所有活動,並得到所有事件和計數之後。真的,我不知道如何在1查詢中正確執行此操作。

+0

'$這個 - > DB-> get_where( 'event_follows',陣列( 'used_id'=> $ USER_ID));',然後你的頭到' $ this-> db-> get_where('events',array('user_id'=> $ user_id);'然後解析它 – 2014-10-31 13:25:38

+0

您期望的O/P plzz? – 2014-10-31 13:27:55

回答

0

我已經做了一些解決方案。但不幸的是它是更復雜的則1查詢:

// Fetch all events which was joined by user 
    $this->db->select('event_id') 
      ->from('event_follows') 
      ->where('user_id', $id); 

    $query1 = $this->db->get(); 
    $result = $query1->result_array(); 

    // Drop keys 
    $joined_events = array();  
    foreach($result as $row) 
    { 
     array_push($joined_events, $row["event_id"]); 
    } 

    // Fetch all events 
    $this->db->select('events.*, COUNT(event_follows.id) as followers') 
      ->from('events') 
      ->where('events.user_id', $id) 
      ->or_where_in('events.id', $joined_events); 
    $this->db->join('event_follows', 'event_follows.event_id = events.id', 'left') 
      ->group_by('event_follows.event_id'); 

    $query2 = $this->db->get(); 
0

雖然我可以從你的問題明白了,我只能想到這個解決方案:

$query = "select e.*, count(e.*), ef.*, count(ef.*) from events e join event_follows ef on ef.user_id = e.user_id where e.user_id = '$my_id' "; 
$data['info'] = $this->db->query($query)->result_array(); 

//Then, you can use php's echo "<pre>", print_r() and die() functions 
//to test the result: 

echo "<pre>"; 
print_r(data['info']); 
die();