Codeigniter group_by 和 Order_by 冲突
Codeigniter group_by and Order_by conflict
我目前正在处理 Codeigniter 查询,我试图从中获得大量结果。但是,当我在同一个查询中同时使用 group_by 和 order_by 时,order_by 被否决并且由于某种原因不适用。
查询如下:
$this->db->select('q.questionNumber, qa.qaId')->from('questions q');
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId');
$this->db->where('customerId', $customerId);
$this->db->order_by('q.questionNumber', 'desc');
$this->db->group_by('q.subject');
$query = $this->db->get();
$query->result();
您可以使用以下方式编写查询:
$query = $this->db->query("SELECT .....");
$query->result();
使用更新的
$this->db->select('q.questionNumber, qa.qaId')->from('questions q');
$this->db->select_max('q.questionNumber' , 'questionNumber'); // added this
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId');
$this->db->where('customerId', $customerId);
$this->db->order_by('q.questionNumber', 'desc');
$this->db->group_by('q.subject');
$query = $this->db->get();
$query->result();
您可以针对您的查询尝试此解决方案:
$this->db->select('q.subject,COUNT(q.questionNumber), COUNT(qa.qaId)')->from('questions q');
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId');
$this->db->where('customerId', $customerId);
$this->db->group_by('q.subject');
$this->db->order_by('q.questionNumber', 'desc');
$query = $this->db->get();
$query->result();
Group By Clause查询和其他带聚合功能的字段查询时必须在选择行中添加列。
我目前正在处理 Codeigniter 查询,我试图从中获得大量结果。但是,当我在同一个查询中同时使用 group_by 和 order_by 时,order_by 被否决并且由于某种原因不适用。
查询如下:
$this->db->select('q.questionNumber, qa.qaId')->from('questions q');
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId');
$this->db->where('customerId', $customerId);
$this->db->order_by('q.questionNumber', 'desc');
$this->db->group_by('q.subject');
$query = $this->db->get();
$query->result();
您可以使用以下方式编写查询:
$query = $this->db->query("SELECT .....");
$query->result();
使用更新的
$this->db->select('q.questionNumber, qa.qaId')->from('questions q');
$this->db->select_max('q.questionNumber' , 'questionNumber'); // added this
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId');
$this->db->where('customerId', $customerId);
$this->db->order_by('q.questionNumber', 'desc');
$this->db->group_by('q.subject');
$query = $this->db->get();
$query->result();
您可以针对您的查询尝试此解决方案:
$this->db->select('q.subject,COUNT(q.questionNumber), COUNT(qa.qaId)')->from('questions q');
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId');
$this->db->where('customerId', $customerId);
$this->db->group_by('q.subject');
$this->db->order_by('q.questionNumber', 'desc');
$query = $this->db->get();
$query->result();
Group By Clause查询和其他带聚合功能的字段查询时必须在选择行中添加列。