Change record status: 
Project: 
Introduced in branch: 
8.3.x
Introduced in version: 
8.3.0
Description: 

DBTNG conditions can now contain subqueries. For instance:

  • Select query at left hand side:
      SELECT ...
      FROM ...
      WHERE (SELECT COUNT(*) FROM ... WHERE ...) > value
      
  • Select query at right hand side:
      SELECT ...
      FROM ...
      WHERE value < (SELECT AVG(...) FROM ...)
      
  • Multiple select queries at right hand side:
      SELECT ...
      FROM ...
      WHERE value BETWEEN (SELECT MIN(...) FROM ...) AND (SELECT MAX(...) FROM ...)
      
  • Select query at left and right hand side (new test):
      SELECT t.name
      FROM test t
      WHERE (SELECT AVG(tt.priority) FROM test_task tt WHERE tt.pid = t.id) > (SELECT AVG(tt2.priority) FROM test_task tt2)
      
  • Select query at left hand side and multiple select queries at right hand side:
      SELECT ...
      FROM ...
      WHERE (SELECT AVG(...) FROM ... WHERE ...) BETWEEN (SELECT MIN(...) FROM ...) AND (SELECT MAX(...) FROM ...)
      

With a code example:

  // Create a subquery, which is just a normal query object.
  $subquery = db_select('test', 't2');
  $subquery->addExpression('AVG(t2.age)');

 // Create another query that adds a clause using the subquery.
  $select = db_select('test', 't');
  $select->addField('t', 'name');
  $select->condition('t.age', $subquery, '<');

  // The resulting query should be equivalent to:
  // SELECT t.name
  // FROM test t
  // WHERE t.age < (SELECT AVG(t2.age) FROM test t2)
Impacts: 
Module developers