Tuesday, July 30, 2013

SQL UNION using Drupal db_select

Here's how to use Drupal's db_select function to perform a SQL UNION like below:

select uid from users where type = 'i'
union
select uid from users_archive where type = 'i'

Bad example, but I can't think of a proper example now :)

Drupal db_select version:

$q1 = db_select('users', 'u')
       ->fields('u', array('uid'))
       ->condition('type', 'i');

$q2 = db_select('users_archive', 'ua')
       ->fields('ua', array('uid'))
       ->condition('type', 'i');

$q1->union($q2);

$results = $q1->execute();

No comments: