2011-08-22 94 views
0

我想連接兩個共享一個公共ID的表,並且它不斷返回多行單個行。爲什麼我的查詢多次返回同一行?

function get_latest_pheeds() { 
    $data = $this->user_keywords($this->ion_auth->user_id); 
    $keyword = $data; 
    $user_id = $this->ion_auth->user_id; 
    foreach($keyword as $key => $word) { 
     $q = "SELECT *,COUNT(pheed_comments.comment_id) as comments 
       FROM pheeds 
       LEFT JOIN pheed_comments ON pheed_comments.P_id=pheeds.pheed_id 
       WHERE pheed LIKE '%$word%' OR user_id='$user_id' 
       ORDER BY datetime DESC"; 
     $result = $this->db->query($q); 
     $rows[] = $result->result(); 
    } 
    return $rows; 
} 

是我的錯查詢:我用笨

這是從模型的功能嗎?

回答

5

您正在爲您的COUNT()

  $q = "SELECT *,COUNT(pheed_comments.comment_id) as comments 
      FROM pheeds 
      LEFT JOIN pheed_comments ON pheed_comments.P_id=pheeds.pheed_id 
      WHERE pheed LIKE '%$word%' OR user_id='$user_id' 
      GROUP BY pheed_id, pheed 
      ORDER BY datetime DESC"; 

缺少GROUP BY現在,因爲你正在使用SELECT *,可能會有更多的列與COUNT()返回。爲了獲得準確的結果,您還必須在GROUP BY中列出它們:

GROUP BY pheed_id, pheed, othercol1, othercol2, othercol3