Home > Backend Development > PHP Tutorial > How to Execute a SELECT Query with a NOT IN Subquery using CodeIgniter Active Record?

How to Execute a SELECT Query with a NOT IN Subquery using CodeIgniter Active Record?

Barbara Streisand
Release: 2024-11-26 11:35:11
Original
471 people have browsed it

How to Execute a SELECT Query with a NOT IN Subquery using CodeIgniter Active Record?

CodeIgniter Active Record: Executing a SELECT Query with a NOT IN Subquery

In this scenario, you want to retrieve all rows from the 'certs' table that are not present in the 'revokace' table. Conventional SQL syntax for this query would be:

SELECT *
FROM certs
WHERE id NOT IN (SELECT id_cer FROM revokace);
Copy after login

To achieve this using CodeIgniter's Active Record pattern, you can utilize the '->where()' method. However, it's important to handle potential conflicts with special characters in your query.

Solution:

CodeIgniter's '->where()' method conveniently supports passing custom query strings directly to the database. This allows you to write your query as:

$this->db->select('*')
         ->from('certs')
         ->where('`id` NOT IN (SELECT `id_cer` FROM `revokace`)', NULL, FALSE);
Copy after login

In this query, the 'NULL,FALSE' arguments ensure that CodeIgniter does not perform any escaping, preserving the integrity of your subquery.

Optional Alternative:

For further code optimization, consider using the CodeIgniter Subquery Library. It simplifies subquery creation by providing a dedicated interface. Your query using the Subquery Library would look like this:

$this->db->select('*')
         ->from('certs');

$sub = $this->subquery->start_subquery('where_in')
                       ->select('id_cer')
                       ->from('revokace');

$this->subquery->end_subquery('id', FALSE);
Copy after login

The above is the detailed content of How to Execute a SELECT Query with a NOT IN Subquery using CodeIgniter Active Record?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template