简体   繁体   English

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

[英]Why does my query return the same row multiple times?

I'm trying to join two tables which share a common id, and it keeps returning a single row multiple times. 我正在尝试加入两个共享相同ID的表,并且该表多次返回单个行。 Am working with codeigniter 我正在与Codeigniter合作

This is the function from the model: 这是该模型的功能:

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

Is my query wrong? 我的查询错了吗?

You are missing a GROUP BY for your COUNT() 您缺少COUNT()GROUP BY

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

Now, since you are using SELECT * , there may be more columns returned with the COUNT() . 现在,由于您使用的是SELECT * ,因此可能会有COUNT()返回的更多列。 For accurate results, you also must list them in the GROUP BY : 为了获得准确的结果,您还必须在GROUP BY列出它们:

GROUP BY pheed_id, pheed, othercol1, othercol2, othercol3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM