How to add union all in codeigniter query?

by edmond_brakus , in category: PHP Frameworks , 9 months ago

How to add union all in codeigniter query?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 9 months ago

@edmond_brakus 

To add UNION ALL in a CodeIgniter query, you can use the union_all() method provided by CodeIgniter's Query Builder class.


Here's an example of how to use UNION ALL in a CodeIgniter query:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$this->db->select('column1, column2');
$this->db->from('table1');
$this->db->where('condition1', 'value1');

$this->db->union_all();

$this->db->select('column1, column2');
$this->db->from('table2');
$this->db->where('condition2', 'value2');

$query = $this->db->get();


In the above example, we first select column1 and column2 from table1 with a specific condition. Then we use the union_all() method to add the UNION ALL keyword in the query. After that, we select the same columns from table2 with a different condition. Finally, we execute the query using the get() method.


Note: Make sure you have loaded the database library in your CodeIgniter application before running the query. You can do this by adding $this->load->database(); in your controller's constructor or in the method where you're running the query.