Codeigniter didn’t provide an option to use subqueries with active record class. So today I would like to provide simple and possible comprehensive techniques on “creating Sub Queries with Codeigniter Active Record”.
Creating subquery in Codeigniter is as easy as creating the regular Active Record queries. The technique here is first we need to generate a query and the generated query we need to inject it into the main query as subQuery.
So first we need to generate a subquery and store that generated the query in a variable as a string. After generating subquery we will generate the main query by using previously generated query as a subquery.
For Example – I am going to generate blow query with active record methods
SELECT * FROM employees WHERE id IN(SELECT id FROM employees_backup);
// Sub Query
$subQuery = $this->db->get_compiled_select();
// Main Query
->where("id IN ($subQuery)", NULL, FALSE)
The NULL, FALSE in the where() method tells CodeIgniter not to escape the query.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.