iserich 发表于 2012-5-17 15:50:00

新手解决AR 使用 group_by 字段函数问题 各位勿笑话

本帖最后由 iserich 于 2012-5-17 15:55 编辑

实际应用中,希望对日期进行 分组操作,按年月,或者年月日操作

sql 大概写成: SELECT DATE_FORMAT( dateline,'%Y%m%d') yyyymm, count( id) count
FROM (`tbl_test`)
WHERE`dateline`>='2012-1-1'
AND`dateline`<'2013-1-1'
GROUPBY DATE_FORMAT( dateline,'%Y%m%d')

于是model写成 :
function getGroupByDate($arr=array()){
      $this->db->select('DATE_FORMAT(dateline,\'%Y%m%d\' ) yyyymm,count(id) count',FALSE)->from(self::TABLE);
      $this->db->where($arr);
      $this->db->group_by("DATE_FORMAT(dateline,'%Y%m%d' )");
      $return = $this->db->get()->result_array();
      return $return;
    }

于是出错了,错误如下:

SELECT DATE_FORMAT(dateline, '%Y%m%d' ) yyyymm, count(id) countFROM (`tbl_test`)WHERE `dateline` >= '2012-1-1'AND `dateline` < '2013-1-1' GROUP BY DATE_FORMAT(dateline, `'%Y%m%d')`

去读DB_activr_rec源码,有这么一段:
/**
   * GROUP BY
   *
   * @param    string
   * @return    object
   */
    public function group_by($by)
    {
      if (is_string($by))
      {
            $by = explode(',', $by);
      }

      foreach ($by as $val)
      {
            $val = trim($val);

            if ($val != '')
            {
                $this->ar_groupby[] = $this->_protect_identifiers($val);

                if ($this->ar_caching === TRUE)
                {
                  $this->ar_cache_groupby[] = $this->_protect_identifiers($val);
                  $this->ar_cache_exists[] = 'groupby';
                }
            }
      }
      return $this;
    }


原因是按逗号进行了分组,说实话,真动了改源代码的心。后来想想,这不科学,还是选择别的方法吧,突然灵光一闪
发现了model里的这句话$this->db->select('DATE_FORMAT(dateline,\'%Y%m%d\' ) yyyymm,count(id) count',FALSE)->from(self::TABLE);

试试用别名可以不,果然可以,,,{:soso_e142:}{:soso_e189:}

于是改成model最终代码:function getGroupByDate($arr=array()){
      $this->db->select('DATE_FORMAT(dateline,\'%Y%m%d\' ) yyyymm,count(id) count',FALSE)->from(self::TABLE);
      $this->db->where($arr);
       $this->db->group_by("yyyymm");
      $return = $this->db->get()->result_array();
      return $return;
    }

这个问题总结起来就是学的不扎实的结果。{:soso_e136:}
被标题吸引过来的大神们,不要笑话{:soso_e120:}

PS:数据库日期是 字符型的,因为是从mssql转过来的。{:soso_e141:}{:soso_e141:}
where条件为空会出错吧。我的model加了一些标志位的判断。所以不会出错。{:soso_e182:}

kissgxd 发表于 2012-5-17 16:49:18

嗯嗯 很不错,我有一次也改过CI源码,不过提心吊胆的

五月杨柳 发表于 2012-5-24 16:16:08

完全是技术流。
页: [1]
查看完整版本: 新手解决AR 使用 group_by 字段函数问题 各位勿笑话