function DatabaseSelectComplexTestCase::testCountQueryGroupBy

Test that we can generate a count query from a query with GROUP BY.

File

modules/simpletest/tests/database_test.test, line 2391

Class

DatabaseSelectComplexTestCase
Test more complex select statements.

Code

function testCountQueryGroupBy() {
    $query = db_select('test_task');
    $pid_field = $query->addField('test_task', 'pid');
    $query->groupBy('pid');
    $count = $query->countQuery()
        ->execute()
        ->fetchField();
    $this->assertEqual($count, 3, 'Counted the correct number of records.');
    // Use a column alias as, without one, the query can succeed for the wrong
    // reason.
    $query = db_select('test_task');
    $pid_field = $query->addField('test_task', 'pid', 'pid_alias');
    $query->addExpression('COUNT(test_task.task)', 'count');
    $query->groupBy('pid_alias');
    $query->orderBy('pid_alias', 'asc');
    $count = $query->countQuery()
        ->execute()
        ->fetchField();
    $this->assertEqual($count, 3, 'Counted the correct number of records.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.