CodeIgniter Forums
Create subquery in WHERE - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Create subquery in WHERE (/showthread.php?tid=86175)



Create subquery in WHERE - motoroller - 01-18-2023

I have subquery like this its working, how i can rewrite with active record?

$builder->where("(SELECT SUM(sum) FROM payments WHERE visit = v.id) > 0");


Like this

$SubQuery = $this->db->table('payments ')->select('SUM(sum)')->where('visit = v.id');


$MainQuery = $this->db->table('visits')->where("$SubQuery > 0")


RE: Create subquery in WHERE - Codinglander - 01-18-2023

Your $SubQuery return not the SQL statement. It returns the result.
You have to use the "getCompiledSelect()" Method for $SubQuery....

https://codeigniter.com/user_guide/database/query_builder.html#builder-getcompiledselect