Home > Backend Development > PHP Tutorial > How Can I Execute UNION Queries Using CodeIgniter's Active Record?

How Can I Execute UNION Queries Using CodeIgniter's Active Record?

Patricia Arquette
Release: 2024-11-20 18:07:24
Original
974 people have browsed it

How Can I Execute UNION Queries Using CodeIgniter's Active Record?

Executing UNION Queries in CodeIgniter's Active Record

CodeIgniter's Active Record pattern provides a powerful way to interact with databases. However, it lacks built-in support for UNION queries. To overcome this limitation, you can directly execute SQL queries using the query method.

Query Syntax

To perform a UNION query using CodeIgniter's Active Record, use the following syntax:

$this->db->query('SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2');
Copy after login

In this query, the column_name(s) represents the columns you want to retrieve, and table_name1 and table_name2 represent the tables to combine.

Example

Consider the following example:

$sql = "SELECT username FROM users
UNION
SELECT username FROM admins";

$query = $this->db->query($sql);
Copy after login

This query will retrieve the username column from both the users and admins tables, combining the results into a single list.

Note:

Remember that UNION queries require the columns in both tables to be of the same data type and order. Otherwise, an error will occur.

The above is the detailed content of How Can I Execute UNION Queries Using CodeIgniter's 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