【问题标题】:unable to count the exact number of rows无法计算确切的行数
【发布时间】:2013-04-14 12:42:44
【问题描述】:

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

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

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

表结构

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


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

Table 数据结构数据:

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

【问题讨论】:

  • @JoachimIsaksson 是的,谢谢。工作正常。我不知道。 left in this join 是什么意思?将其发布为几乎没有解释的答案。这样我才能接受你的回答
  • @BurlsWillis MySQL LEFT JOIN,准备好documentation about it
  • @BurlsWillis 当然,添加了答案。

标签: php mysql codeigniter


【解决方案1】:

你应该使用左连接

$this->db->join('answer','answer.question_id = question.question_id','LEFT'); 

【讨论】:

    【解决方案2】:

    你需要的是一个LEFT JOIN,这基本上意味着如果第一个提到的表中有一行存在,那么第二个表中的对应行是不需要的。在您的情况下,如果有问题,即使没有匹配的答案也会返回。

    要在 codeigniter 中进行左连接,您只需将“左”作为第三个参数传递给您对 join 的调用;

    $this->db->join('answer','answer.question_id = question.question_id', 'left');
    

    有关加入通话的更多信息,请访问at the CodeIgniter docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多