Drupal - How do I write a left join query?

$terms = db_select('taxonomy_index', 'ti')
  ->fields('ti', array('tid', 'name'));
$terms->leftJoin('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
$terms->condition('vid', 2)
  ->condition('nid', $nid)
  ->execute();

while ($term = $terms->fetch()) {
  // $term contains the object for the taxonomy term.
}

You do not need to use db_select() for a static query like this. You shouldn't, actually, see Given that db_select is much slower than db_query, why would I want to use it?.

You just need to pass that to db_query(), the only thing that changed is how you add placeholders.

$result = db_query('select tid,name from {taxonomy_index} as ti left join {taxonomy_term_data} as ttd on ti.tid=ttd.tid where vid=2 and nid=:nid', array(':nid' => $nid));
foreach ($result as $term) {
  // $term contains the object for the taxonomy term.
}

See http://drupal.org/developing/api/database for more information and my blog post for generic Drupal 6 to 7 database syntax conversion information.

Tags:

Database

7