1

我编写了一个模型代码,我将在其中加入两个表,并返回我的结果。

我的表中有 26 个结果,但我提到的下面的代码只返回一行!可能是什么原因?为什么它只返回一行?

请帮我解决这个问题

更新

表结构

question
-----------
question_id PK Auto_Incr  
question    varchar... 
votes       int


answer
------------
answer_id    PK  Auto_icre
question_id  FK refrences question  
content      longtext

answer从下表结构中,我的模型代码仅显示 2 个问题计数,跳过最后一个问题,经过少量研究,我发现它不计算我的第三个问题的原因是因为它在我的表中没有任何答案。

我想,如果没有答案,那么它应该为特定问题显示 count=0,如何解决这个问题?


表数据结构数据:

 question
-----------
 question_id    question          votes
    1           what's name?       0
    2           where you?         3
    3           blah blah          9 

answer 
----------
 answer_id      question_id        content
    4              2                 India
    5              2                 Nepal
    6              2                 Pakistan
    7              1                 Mr Osama Binladan

模型

       public function fetch_allquestions($limit, $start) 
{
    $this->load->database(); 
    $this->db->limit($limit, $start);   
     $this->db->from('question');
    $select =array(
                    'question.*',
                    'userdetails.*',
                    'COUNT(answer.answer_id) AS `Answers`'
            );

    $this->db->select($select);

    $this->db->join('answer','answer.question_id = question.question_id'); 
    $this->db->join('userdetails','userdetails.user_id = question.user_id'); 
     $query = $this->db->get();

    print_r("Number of rows=".$query->num_rows());//showing only One, out of 26 rows


    if ($query->num_rows() > 0)
    {
        foreach ($query->result() as $row)
            {
                $data[] = $row;
            }
            return $data;
    }else{
        return false;
    }
}
4

1 回答 1

2

COUNT()在选择中有一个 sql 聚合。由于您没有任何GROUP BY,因此数据库会将整个结果集用作一个隐式组,从而在将结果集全部计数时将结果集减少到一行。这就是sql应该如何工作。

print $this->db->last_query()您可以在该行之后检查生成的 sql 查询$this->db->get();,并在您的 sql 控制台中运行它以查看发生了什么。

您可能想添加一个$this->db->group_by('question.question_id');或类似的东西。

于 2013-04-14T08:37:31.360 回答