Excluding specific user role from query I have this query, which fetches all users with the role #7.

$query = 'SELECT DISTINCT(ur.uid) 
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids)';

$result = db_query($query, array(':rids' =&gt; array(7)));


Some users currently have both roles #7 and #8. I beleive they are all fetched by this query. I would like to exclude users with the role #8. 

Can someone help me?
Try

$query = 'SELECT DISTINCT(ur.uid) 
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids) AND ur.rid NOT IN (:rids2)';

$result = db_query($query, array(':rids' =&gt; array(7), ':rids2' =&gt; array(8)));


Or if you wanted just the more specific version

$query = 'SELECT DISTINCT(ur.uid) 
  FROM {users_roles} AS ur
  WHERE ur.rid = (:rids) AND ur.rid != (:rids2)';

$result = db_query($query, array(':rids' =&gt; 7, ':rids2' =&gt; 8));