Community

How do I convert "COUNT(*) AS num" into the D7 API syntax?

How do I convert "COUNT(*) AS num" into the D7 API syntax. Following is what I have so far, but I'm not sure about the way I have added the COUNT expression:

<?php
   
// D6 version of query:
//     db_query(
//       'INSERT INTO {statspro_term} (tid, ncount)
//         SELECT tid, COUNT(*) AS num
//         FROM {term_node}
//         GROUP BY tid'
//     );

    // D7 version of query?
   
$query = db_select('taxonomy_term_node')
    ->
fields(array('tid'))
    ->
groupBy('tid');
   
$query->addExpression("COUNT(*) as num");
   
   
db_insert('statspro_term')
    ->
from($query)
    ->
execute();
?>

Thanks!

Comments

It should be

It should be like:
$query->addExpression('COUNT(*)', 'num');

nobody click here