function SelectSubqueryTest::testConditionSubquerySelect

Tests that we can use a subquery in a WHERE clause.

File

drupal/core/modules/system/lib/Drupal/system/Tests/Database/SelectSubqueryTest.php, line 86
Definition of Drupal\system\Tests\Database\SelectSubqueryTest.

Class

SelectSubqueryTest
Tests for subselects in a dynamic SELECT query.

Namespace

Drupal\system\Tests\Database

Code

function testConditionSubquerySelect() {

  // Create a subquery, which is just a normal query object.
  $subquery = db_select('test_task', 'tt');
  $subquery
    ->addField('tt', 'pid', 'pid');
  $subquery
    ->condition('tt.priority', 1);

  // Create another query that joins against the virtual table resulting
  // from the subquery.
  $select = db_select('test_task', 'tt2');
  $select
    ->addField('tt2', 'task');
  $select
    ->condition('tt2.pid', $subquery, 'IN');

  // The resulting query should be equivalent to:
  // SELECT tt2.name
  // FROM test tt2
  // WHERE tt2.pid IN (SELECT tt.pid AS pid FROM test_task tt WHERE tt.priority=1)
  $people = $select
    ->execute()
    ->fetchCol();
  $this
    ->assertEqual(count($people), 5, 'Returned the correct number of rows.');
}