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');
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);
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!