count with distinct for 1 column

Hey guys,

I know, this is a stupid question, but I just can’t make it run.

The thing i want is: I got a table where entries from users are saved in and now I need a function to get all users (unique) with distinct. So every user just counts as "1" user.

The method i got at the moment looks as follows, but the distinct just doesn’t want to work. :frowning:

public static function getAllVisitors()


        $columns = array();

        $columns[] = 'user_number';

        $criteria = new CDbCriteria;

        $criteria->select = $columns;


        $count = self::model()->count($criteria);

        return $count;


Thanks in advance,


Try adding:

$criteria->distinct = true;

ohh forgot to post that in my method … already tried this --> doesn’t work :-(. Still counts every row including the duplicates

Obviously In this case (not the implicit PK) the count() method don’t use the distinct property of the criteria. The count() method ignores the select criteria.

I probably would choose this workaround since it doesn’t need a column alias to be declared


  $attribute = 'user_number';

  $sql = 'SELECT COUNT(DISTINCT '.$attribute.') FROM '.self::model()->tableName();

  $count = self::model()->getCommandBuilder()->createSqlCommand($sql)->queryScalar();



Thanks a lot Tommy, it’s net the finest solution, but it works and i think in this case I can leave it like this :slight_smile:

… did I say yet, that I love Yii and this forum?!? … You guys are awesome!