由不在php codeigniter工作的排序和分组?

时间:2016-11-03 07:05:17

标签: php sql codeigniter

表格格式: 表名类别:

      id       title
   -----------------
      1          xyz
      2          abc

表名子类别:

     id        category_id    start_date      status
 ----------------------------------------------------------
     1             1            2016-11-03       1
     2             1            2016-11-09       1
     3             2            2016-10-03       1
     4             3            2016-12-03       1
     5             3            2016-12-05       1
     6             5            2016-12-06       1

查询:

      $date = date('Y-m-d');
      $this->db->select('*');
      $this->db->where('status',1);
      $this->db->where('start_date >=',$date);
      $this->db->order_by('start_date', 'asc');
      $this->db->group_by('category_id');
      $this->db->limit(4);
      $query = $this->db->get('subcategory');
      return $query->result();

我的问题是:我希望结果为subcategory_id 1,4,6。但是group_by和order by不起作用。

错误:

  

SELECT列表不在GROUP BY子句中,并且包含nonaggregated   列'dbname.subcategory.id',它在功能上不依赖于   GROUP BY子句中的列;这是不相容的   sql_mode = only_full_group_by SELECT * FROM(subcategory)WHERE status =   1 AND start_date> ='2016-11-03'GROUP BY category_id ORDER BY   start_date asc LIMIT 4

2 个答案:

答案 0 :(得分:0)

更改您的查询

首先按顺序排列
$date = date('Y-m-d');
$this->db->select('*');
$this->db->where('status',1);
$this->db->where('start_date >=',$date);
$this->db->group_by('category_id');
$this->db->order_by('start_date', 'asc');
$this->db->limit(4);
$query = $this->db->get('subcategory');
return $query->result();

或者在$query之后执行此操作来打印查询,并在数据库中检查相同内容:

echo $this->db->last_query();

答案 1 :(得分:0)

$date = date('Y-m-d');
$this->db->select('*');
$this->db->group_by('category_id');
$this->db->limit(4);
$query = $this->db->get("(SELECT * FROM subcategory where status=1 and start_date>='$date' order by start_date) as subcategory");
return $query->result();