Drupal 7 inner join usage example

Warning message

JQuery Cycle must be installed in order to run the slideshow. Please go to Status Report for instructions.

Primary tabs

Here is the example function of inner join usage in Drupal 7. In this example we are fetching first and last name from database which we have already added in user entity.

 $matches = array();
 $select = db_select('users', 'u');
// Create inner join on table field_data_field_first_name
 $select->innerjoin('field_data_field_first_name', 'fn', 'fn.entity_id = u.uid'); 
// Create inner join on table field_data_field_last_name
 $select->innerjoin('field_data_field_last_name', 'ln', 'ln.entity_id = u.uid');  
 $select->fields('u', array('uid', 'name'))
           ->fields('fn', array('field_first_name_value'))
           ->fields('ln', array('field_last_name_value'))
           ->condition('status', 1)
           ->condition('field_first_name_value', '%' . db_like(check_plain($string . '')) . '%', 'LIKE')
           ->orderBy('field_first_name_value')
           ->range(0, 10);

 $result = $select->execute()->fetchAllAssoc('uid');

    foreach ($result as $patron) {
      if (isset($patron->field_first_name_value) && isset($patron->uid)) {
        $matches[$patron->field_first_name_value . '-' . $patron->field_last_name_value . ' [uid:' . $patron->uid . ']'] = check_plain($patron->field_first_name_value) . '-' . check_plain($patron->field_last_name_value);
      }
    }