为什么我的查询多次返回同一行?

时间:2011-08-22 17:51:18

标签: php mysql codeigniter

我正在尝试连接两个共享一个公共ID的表,并且它会多次返回一行。我正在使用codeigniter

这是该模型的功能:

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;
}

我的查询错了吗?

1 个答案:

答案 0 :(得分:5)

您遗失了GROUP BY

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";

现在,由于您使用的是SELECT *,因此COUNT()可能会返回更多列。要获得准确的结果,您还必须在GROUP BY

中列出这些结果
GROUP BY pheed_id, pheed, othercol1, othercol2, othercol3