加入查询和group_by

时间:2011-12-04 10:34:38

标签: sql codeigniter join group-by

我有两张桌子'city'和'info'。城市看起来像

                  city_id    name
                   1         c1
                   2         c2

信息看起来像

                  id   city_city_id   status_status_id
                  1     1              1
                  2     2              1
                  3     1              2

在info表中,City_city_id和status_status_id是fks。我想运行一个查询来计算特定状态下的城市数量。为此,我加入了两个表格,并且对于'city'表格的每一行,我都运行了一个查询但是我一直得到答案00.这意味着它总是显示特定状态下的城市数量为零。 / p>

该模型如下:

            function count(){
           $this->db->select('*');
           $this->db->from('city');
           $this->db->join('info','info.city_city_id= city.city_id');
           $this->db->group_by('city_city_id');
           $sql=$this->db->get();
           if ($sql->num_rows()>0){ 

          foreach ($sql->result() as $row){ //loops through all the cities in city table
          $r=1;

      $this->db->where('city_city_id','city.city_id');

       $this->db->where('status_status_id', $r);
      echo $this->db->count_all_results('info');


} 

我认为我的加入和group_by有问题,但我找不到错误。 提前致谢。

1 个答案:

答案 0 :(得分:1)

所以你想要

I want to run a query that would count the number of cities 
under a particular status.

即,您需要状态和属于该状态的城市数量。对?然后,以下SQL查询将适用于您:

SELECT status_status_id, count( * ) AS num_cities
FROM info
GROUP BY status_status_id

会给出结果:

status_status_id    num_cities
       1                2
       2                1

然后,您可以使用以下内容:

function count() {
    $this->db->select('status_status_id, count( * ) AS num_cities', FALSE);
    $this->db->from('info');
    $this->db->group_by('status_status_id');

    $query = $this->db->get('mytable');
    foreach ($query->result() as $row)
    {
        echo 'STATUS_ID : ' . $row->status_status_id . "\n";
        echo 'NUM_CITIES: ' . $row->num_cities . "\n";
    }
}