by changing the somnath huluks answer, I add the following variables and functions to the DB_Active_rec class as follows:
class DB_Active_records extends CI_DB_Driver { .... var $unions; .... public function union_push($table = '') { if ($table != '') { $this->_track_aliases($table); $this->from($table); } $sql = $this->_compile_select(); array_push($this->unions, $sql); $this->_reset_select(); } public function union_flush() { $this->unions = array(); } public function union() { $sql = '('.implode(') union (', $this->unions).')'; $result = $this->query($sql); $this->union_flush(); return $result; } public function union_all() { $sql = '('.implode(') union all (', $this->unions).')'; $result = $this->query($sql); $this->union_flush(); return $result; } }
therefore, you can practically use unions without dependencies on db_driver.
to use a connection with this method, you simply make regular active write requests, but call union_push instead of get.
Note: you must ensure that your queries have the appropriate columns, for example, regular unions
Example:
$this->db->select('l.tpid, l.lesson, l.lesson_type, l.content, l.file'); $this->db->where(array('l.requirement' => 0)); $this->db->union_push('lessons l'); $this->db->select('l.tpid, l.lesson, l.lesson_type, l.content, l.file'); $this->db->from('lessons l'); $this->db->join('scores s', 'l.requirement = s.lid'); $this->db->union_push(); $query = $this->db->union_all(); return $query->result_array();
will create:
(SELECT `l`.`tpid`, `l`.`lesson`, `l`.`lesson_type`, `l`.`content`, `l`.`file` FROM `lessons` l WHERE `l`.`requirement`=0) union all (SELECT `l`.`tpid`, `l`.`lesson`, `l`.`lesson_type`, `l`.`content`, `l`.`file` FROM `lessons` l JOIN `scores` s ON `l`.`requirement`=`s`.`lid`)