I'm trying to get mysql query into Code Igniter's Active Record syntax but am having a bit of a hard time.
The query is as a result of this question: Multiple mysql ORDER BY's for multidimensional ordering/grouping
I've attempted to format the query myself, have tackled a couple of errors, but am unsure how to progress. I had to add in the get_compiled_select()
function to DB_active_rec.php
myself and change the _reset_select()
from protected to public to get it to run at all.
The suggested query is:
select
t.id,
t.group,
t.date,
t.comlete
from
YourTable t
left join
(select
m.group,
min(m.date) as mindate,
min(t.complete) as groupcomplete
from
YourTable m) mt on mt.group = t.group
order by
coalesce(mt.groupcomplete, t.complete),
coalesce(mt.mindate, t.date),
t.group,
t.complete,
t.date
My translation looks like this (note that there's a 'where' clause not in the original, and that 'date' is actually 'due'):
// Sub query
$this->db->select('m.group, min(m.due) as mindate, min(t.complete) as groupcomplete');
$this->db->from('task m');
$this->db->where('property', $property);
$subquery = $this->db->get_compiled_select();
$this->db->_reset_select();
// Main query
$this->db->select('*');
$this->db->where('property', $property);
$this->db->from('task t');
$this->db->join('($subquery) mt','mt.group = t.group');
$this->db->order_by('coalesce(mt.groupcomplete, t.complete)');
$this->db->order_by('coalesce(mt.mindate, t.due)');
$this->db->order_by('t.group');
$this->db->order_by('t.complete');
$this->db->order_by('t.due');
$query = $this -> db -> get();
// Return
return $query->result();
Unfortunately this is just throwing an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.gr' at line 3
The query as reported by CI looks like:
SELECT * FROM (`task` t) JOIN ($subquery) mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.groupcomplete, `t`.`complete)`, coalesce(mt.mindate, `t`.`date)`, `t`.`due`, `t`.`complete`, `t`.`date`
Anyone able to lend some advice as to how to get this formatted correctly? My mysql skills are, unfortunately, pretty bare, so this is pushing my abilities. Much of the approach of my translation is from answers on Stack Overflow, as I have no experience combining queries in this way (with the subquery).