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

MrF*_*Foh 0 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;
}
Run Code Online (Sandbox Code Playgroud)

我的查询错了吗?

Mic*_*ski 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";
Run Code Online (Sandbox Code Playgroud)

现在,既然你正在使用SELECT *,可能会有更多列返回COUNT().要获得准确的结果,您还必须将它们列在GROUP BY:

GROUP BY pheed_id, pheed, othercol1, othercol2, othercol3
Run Code Online (Sandbox Code Playgroud)