Codeigniter SUM查询只带来一行

问题描述 投票:0回答:1

当我在Codeigniter SELECT中添加SUM时,它只返回一行。但是当我删除它时,它会返回所有可能的匹配条目。

$this->db->where('posts.status',1)
     ->select('posts.title')
     ->select('posts.description')
     ->select('posts.posted_by')
     ->select('posts.posted_on')
     ->select('posts.category')
     ->from('posts')

     ->join('categories','posts.category=categories.id','LEFT')
     ->select('categories.title as cat_title')

     ->join('users','users.id=posts.posted_by','LEFT')
     ->select('users.username')
     ->select('users.first_name')
     ->select('users.last_name')

     // this section is causing to return only one entry/row, 
     // when I remove/comment this section, it brings the desired results
     ->join('votes','votes.post_id=posts.id',"LEFT")
     ->select('SUM(upvote) as upvote_count')
     ->select('SUM(downvote) as downvote_count')

     ->get()
     ->result_object();
database codeigniter mysqli codeigniter-3 codeigniter-2
1个回答
0
投票

尝试添加:

->group_by('posts.id')

->select('SUM(downvote) as downvote_count')

所以现在查询将是:

$this->db->where('posts.status',1)
    ->select('posts.title')
    ->select('posts.description')
    ->select('posts.posted_by')
    ->select('posts.posted_on')
    ->select('posts.category')
    ->from('posts')

    ->join('categories','posts.category=categories.id','LEFT')
    ->select('categories.title as cat_title')

    ->join('users','users.id=posts.posted_by','LEFT')
    ->select('users.username')
    ->select('users.first_name')
    ->select('users.last_name')

    // this section is causing to return only one entry/row, 
    // when I remove/comment this section, it brings the desired results
    ->join('votes','votes.post_id=posts.id',"LEFT")
    ->select('SUM(upvote) as upvote_count')
    ->select('SUM(downvote) as downvote_count')
    ->group_by('posts.id')

    ->get()
    ->result_object();
© www.soinside.com 2019 - 2024. All rights reserved.