Home >Backend Development >PHP Tutorial >How to Use NOT IN Subqueries with CodeIgniter\'s Query Builder?
In database operations, it's often necessary to perform conditional selections based on data retrieved from other tables. MySQL's NOT IN subquery offers a way to exclude rows from a primary query based on their absence in a subquery.
CodeIgniter Implementation
To replicate the MySQL query mentioned in the question:
SELECT *<br>FROM certs<br>WHERE id NOT IN (SELECT id_cer FROM revokace);<br>
using CodeIgniter's query builder methods, you can employ the following approach:
$this->db->select('*') ->from('certs') ->where('`id` NOT IN (SELECT `id_cer` FROM `revokace`)', NULL, FALSE);
The where() method allows for directly passing any string to be incorporated into the query, avoiding potential conflicts with CodeIgniter's escaping mechanisms. However, it's advised to exercise caution when using this approach with user-supplied inputs to prevent SQL injection attacks.
Optimized Subquery Library
Alternatively, consider utilizing a specialized subquery library that can enhance code readability and simplify complex queries. The example given would translate to the following:
$this->db->select('*') ->from('certs') ->where('id', $this->subquery->subquery('where_in', function ($subq) { $subq->select('id_cer') ->from('revokace'); }, 'id', FALSE));
This library simplifies the construction of subqueries and enables more flexible and expressive SQL statements. Whether you opt for the direct string approach or utilize a library, these methods empower you to effectively implement NOT IN subqueries in CodeIgniter.
The above is the detailed content of How to Use NOT IN Subqueries with CodeIgniter\'s Query Builder?. For more information, please follow other related articles on the PHP Chinese website!