Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it important to use base table for entity in query? For example if I want to get all user's id of specific role, should I do:

  $query = db_select('users', 'u');
  $query->distinct();
  $query->fields('u', array('uid'));
  $query->innerJoin('users_roles', 'r', 'u.uid = r.uid');
  $query->condition('r.rid', 3);

or

  $query = db_select('users_roles', 'r');
  $query->fields('r', array('uid'));
  $query->condition('r.rid', 3);
share|improve this question
up vote 5 down vote accepted

No, it's not important, nor necessary.

There's no API method for getting this information, so going directly into the database is fair game. Once you're going directly into the database, you only need to include the tables and fields that your data requires - anything else is a waste of resources.

In this case, you don't need to select or filter anything from the users table, so there's no need to join it in (unless you're worried about referential integrity, and want to make sure the user record actually exists).

share|improve this answer

In your case, the second query is enough, unless you need additional filtering/conditions that depend on the base table (e.g. to select only active users).

Generally speaking, core base tables can have certain tags that give you additional processing/filtering out of the box. The best example is the node_access tag, which if you add to a query that runs against {node} table, will automatically perform node access checks, and fetch only the nodes currently active user has access to. This might be something to consider if you're querying node-related information.

You can read more about query alteration (tagging) here.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.