CodeIgniter Forums
can i use SQL UNION Syntax with CI query builder - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: can i use SQL UNION Syntax with CI query builder (/showthread.php?tid=62964)



can i use SQL UNION Syntax with CI query builder - ngangchill - 09-12-2015

someone help me how can i use SQL UNION Syntax with CI query builder.... Confused


RE: can i use SQL UNION Syntax with CI query builder - ivantcholakov - 09-12-2015

UNION is not supported directly by the query builder as far as I know. On CI3 I apply something like this:

Code:
$tables = array();

        $tables[] = 'table1';
        $tables[] = 'table2';
        $tables[] = 'table3';

        $subqueries = array();

        foreach ($tables as $t) {

            // Change these queries accordingly:
            $this->db
                ->select('category_id')
                ->from($t)
                ->where('sp_id', $sp_id);

            $subqueries[] = '('.$this->db->get_compiled_select().')';
        }

        $sql = implode(' UNION ', $subqueries);
        // or if necessary:
        //$sql = implode(' UNION DISTINCT ', $subqueries);

        $result = $this->db->query($sql)->result_array();



RE: can i use SQL UNION Syntax with CI query builder - ngangchill - 09-12-2015

Thanks. Smile