public function count($criteria=null)
	{
		$query=new CJoinQuery($this,$criteria);
		// ensure only one big join statement is used
		$this->_finder->baseLimited=false;
		$this->_finder->joinAll=true;
		$this->buildQuery($query);

		$query->limit=$query->offset=-1;

		if(!empty($criteria->group) || !empty($criteria->having))
		{
			$query->orders = array();
			$command=$query->createCommand($this->_builder);
			$sql=$command->getText();
			$sql="SELECT COUNT(*) FROM ({$sql}) sq";
			$command->setText($sql);
			$command->params=$query->params;
			return $command->queryScalar();
		}
		else
		{
			$select=is_array($criteria->select) ? implode(',',$criteria->select) : $criteria->select;
			if($select!=='*' && preg_match('/^count\s*\(/i',trim($select)))
				$query->selects=array($select);
			elseif(is_string($this->_table->primaryKey))
			{
				$prefix=$this->getColumnPrefix();
				$schema=$this->_builder->getSchema();
				$column=$prefix.$schema->quoteColumnName($this->_table->primaryKey);
				$query->selects=array("COUNT(DISTINCT $column)");
			}
			else
				$query->selects=array("COUNT(*)");

			$query->orders=$query->groups=$query->havings=array();
			$command=$query->createCommand($this->_builder);
			return $command->queryScalar();
		}
	}