Подсчёт количества записей в БД

@param string $table      Имя таблицы
@param string $condition  Условие для включения в подсчёт

@return int Количество записей, удовлетворяющих условию
967771
public function dbCount($table, $condition = '')
    {
        $result = Eresus_CMS::getLegacyKernel()->db->count($this->__table($table), $condition);

        return $result;
    }
1184923
public function delete($condition)
    {
        $result = null;
        $this->hook->attach('product.class.field.delete.before', $condition, $result, $this);

        if (isset($result)) {
            return (bool) $result;
        }

        if (!is_array($condition)) {
            $condition = array('product_class_field_id' => $condition);
        }

        $result = (bool) $this->db->delete('product_class_field', $condition);
        $this->hook->attach('product.class.field.delete.after', $condition, $result, $this);
        return (bool) $result;
    }
714526
protected function CreateDelete(Table $table, Condition $condition = null, OrderList $orderList = null, $offset = 0, $count = 0)
    {
        return new Delete($this->connection, $table, $condition, $orderList, $offset, $count);
    }
650914
public function GetCount($Table = '', $Where = FALSE) {
      if($Table != '') {
         //$this->MapAliases($Table);
         $this->From($Table);
      }

      if ($Where !== FALSE)
         $this->Where($Where);

      $this->Select('*', 'count', 'RowCount'); // count * slow on innodb
      $Sql = $this->GetSelect();
      $Result = $this->Query($Sql);

      $CountData = $Result->FirstRow();
      return $CountData->RowCount;
   }
444045
public function hasTable($table)
    {
        $sql = $this->grammar->compileTableExists();

        $table = $this->connection->getTablePrefix().$table;

        return count($this->connection->select($sql, array($table))) > 0;
    }
244057
public static function getRowCount( $table, $type = 'row' ) {

		$stat = self::find()->where( '`table`=:table AND type=:type', [ ':table' => $table, ':type' => $type ] )->one();

		if( isset( $stat ) ) {

			return $stat->count;
		}

		return 0;
	}
719631
public function count($table = '', $where = '')
    {
        // if table name not pass
        if (!empty($table)) {
            if (empty($where)) {
                $this->sql = "SELECT COUNT(*) AS NUMROWS FROM `$table`;"; // create count query
            } else {
                $this->sql = "SELECT COUNT(*) AS NUMROWS FROM `$table` WHERE $where;";  // create count query
            }

            // pdo prepare statement
            $this->STH = $this->prepare($this->sql);

            try {
                if ($this->STH->execute()) {
                    // fetch array result
                    $this->results = $this->STH->fetch();
                    // close pdo
                    $this->STH->closeCursor();
                    // return number of count
                    return $this->results['NUMROWS'];
                } else {
                    self::error($this->STH->errorInfo());
                }
            } catch (\PDOException $e) {
                // get pdo error and pass on error method
                self::error($e->getMessage() . ': ' . __LINE__);
            }
        } else {
            self::error('Table name not found..');
        }
    }
569093
public int queryObjCountByCondition(String tableName, String condition){
		/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
		.getDbSource(dbName);*/
		//String tableName=changeTableNameCase(otableName);
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		String sql="";
		sql="select count(1) from " + tableName + " where "+condition;
		logger.debug(sql);
		Integer total=jdbcTemplate.queryForObject(sql,Integer.class);
		return total;
	}
96627
public function actionCreate(string $table): int
    {
        $tables = [$table];
        if (strpos($table, ',') !== false) {
            $tables = explode(',', $table);
        }

        $migrationsGenerated = 0;
        foreach ($tables as $name) {
            $this->stdout(" > Generating create migration for table '{$name}' ...", Console::FG_YELLOW);

            $className = 'm' . gmdate('ymd_His') . '_create_table_' . $name;
            $file = Yii::getAlias($this->workingPath . DIRECTORY_SEPARATOR . $className . '.php');

            $generator = new Generator([
                'db' => $this->db,
                'view' => $this->view,
                'useTablePrefix' => $this->useTablePrefix,
                'templateFile' => $this->templateFile,
                'tableName' => $name,
                'className' => $className,
                'namespace' => $this->migrationNamespace,
                'generalSchema' => $this->generalSchema,
                'tableOptionsInit' => $this->tableOptionsInit,
                'tableOptions' => $this->tableOptions,
            ]);

            if ($generator->tableSchema === null) {
                $this->stdout("ERROR!\n > Table '{$name}' does not exist!\n\n", Console::FG_RED);

                return ExitCode::DATAERR;
            }

            if ($this->generateFile($file, $generator->generateMigration()) === false) {
                $this->stdout("ERROR!\n > Migration file for table '{$name}' can not be generated!\n\n", Console::FG_RED);

                return ExitCode::SOFTWARE;
            }

            $migrationsGenerated++;

            $this->stdout("DONE!\n", Console::FG_GREEN);
            $this->stdout(" > Saved as '{$file}'\n");

            if ($this->fixHistory) {
                if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
                    $this->createMigrationHistoryTable();
                }

                $this->addMigrationHistory($className, $this->migrationNamespace);
            }

            $this->stdout("\n");
        }

        if ($migrationsGenerated) {
            $this->stdout(" Generated $migrationsGenerated file(s).\n", Console::FG_YELLOW);
            $this->stdout(" (!) Remember to verify files before applying migration.\n\n", Console::FG_YELLOW);
        } else {
            $this->stdout(" No files generated.\n\n", Console::FG_YELLOW);
        }

        return ExitCode::OK;
    }
683639
private function _prepareJoinCondition(array $condition)
	{
		if(count($condition) === 1)
		{
			return $this->condition = '(' . $condition[0]->getColumnName() . ')';
		}

		return $this->condition =
			$condition[0]->getTableName() . '.' . $condition[0]->getColumnName() . ' = ' . $condition[1]->getTableName()
			. '.' . $condition[1]->getColumnName();
	}
482700
protected function aggregate(ConditionInterface $condition)
    {
        if (!$condition->getParameters()) {
            return '';
        }

        $this->aggNumber++;
        $prefix = str_repeat('_', $this->aggNumber);
        $qb = $this->cloneQb($this->queryBuilder);

        $this->resetSqlParts($qb)
            ->select(sprintf('DISTINCT %s%s', $prefix, $this->aliasDotPrimary()))
            ->addGroupBy(sprintf('%s%s', $prefix, $this->aliasDotPrimary()));
        /** @var From $fromPart */
        foreach ($this->getSqlPart($this->queryBuilder, 'from') as $fromPart) {
            /** @var Base $newFrom */
            $newFrom = new From($fromPart->getFrom(), $prefix.$fromPart->getAlias());
            $qb->add('from', $newFrom, true);
        }
        foreach ($this->getSqlPart($this->queryBuilder, 'join') as $rootAlias => $joinPart) {
            /** @var Join $subPart */
            foreach ($joinPart as $subPart) {
                $join = new Join(
                    $subPart->getJoinType(),
                    $prefix.$subPart->getJoin(),
                    $prefix.$subPart->getAlias()
                );
                /** @var Base $newJoin */
                $newJoin = [$prefix.$rootAlias => $join];
                $qb->add('join', $newJoin, true);
            }
        }

        $newParameters = [];
        foreach ($condition->getParameters() as $paramName => $paramValue) {
            $newParameters[str_replace(':', ':'.$prefix, $paramName)] = $paramValue;
        }

        if (count($newParameters) === 2 && stripos($condition->getComparisonOperator(), Condition::BETWEEN) !== false) {
            $newParameterName = implode(' AND ', array_keys($newParameters));
        } else {
            $newParameterName = key($newParameters);
        }

        $qb->andHaving($condition->getSqlFunctionDefinition($newParameterName, $prefix))->setParameters([]);

        foreach ($newParameters as $paramName => $paramValue) {
            $parameter = new Parameter($paramName, $paramValue);
            $this->parameters->add($parameter);
        }

        return sprintf('%s IN(%s)', $this->aliasDotPrimary(), $qb->getDQL());
    }
417755
public function count($condition)
	{
		$words = explode(' ', $condition);
		for ($i = 0; $i < count($words); $i+=2)
		{
			// odd parts (modules)
			$name = strtolower($words[$i]);
			$words[$i] = count($this->byPosition($name));
		}

		$str = 'return ' . implode(' ', $words) . ';';

		return eval($str);
	}
315252
public function update($table, $set, $condition)
	{
        Eresus_Kernel::log(__METHOD__, LOG_NOTICE, 'This method is deprecated');
		$q = Eresus_DB::getHandler()->createUpdateQuery();
		$q->update($table)
			->where($condition);

		$set = explode(',', $set);
		foreach ($set as $each)
		{
			list($key, $value) = explode('=', $each);
			$key = str_replace('`', '', trim($key));
			$value = preg_replace('/(^\'|\'$)/', '', trim($value));
			$q->set($key, $q->bindValue($value));
		}

        $q->execute();
	}
513519
public static function update($table, $record, $condition = null)
    {
        if(empty($record) || empty($condition)) return null;

        $query = array("UPDATE $table SET ");
        array_push($query, implode('=? , ', array_keys($record)));
        array_push($query, "=? WHERE $condition");
        return implode($query);
    }
1153247
public static function first($table, $field, $condition)
    {
        $db = self::Using(self::$using_dbo_id);
        return $db->resultFirst($table, $field, $condition);
    }
906651
public static function count($condition, $params = array())
    {
        if (!is_a($condition, '\\mpf\\datasources\\sql\\ModelCondition')) {
            $condition = ModelCondition::getFrom($condition, get_called_class());
        }
        /* @var $condition ModelCondition */
        $condition->fields = 'COUNT(*) as number';
        $condition->setParams($params);
        $number = static::getDb()->queryAssoc($condition->__toString(true), $condition->getParams());
        return $number[0]['number'];
    }
168809
private function buildCondition($condition) 
    {
        $where = '';
        
        foreach($condition as $filter) {
            switch(count($filter)) {
                case 1:
                $where .= ' ' . $this->validateLogicalOperator(($filter[0])) . ' ';
                break;
                case 3:
                $where .= $this->quoteColumnName($filter[1]) .' '. $this->validateComparisonOperators($filter[0]) .' '. $this->handleThridParameter($filter[2]);
                break;
                case 4:
                $where .= $this->quoteColumnName($filter[1]) .' '. $this->validateComparisonOperators($filter[0]) .' '. $this->quoteValue($filter[2]) . ' AND ' . $this->quoteValue($filter[3]);
                break;
            }
        }
        
        return $where;
    }