select语句

@return string
327654
protected function getSelectString(): string
    {
        $statement = '';
        $fieldSelect    = $this->builder->getSelect();
        $aggregate = $this->builder->getAggregate();
        if (empty($fieldSelect) && empty($aggregate)) {
            return $statement;
        }

        $select = $this->getAggregateStatement($fieldSelect, $aggregate);

        // 字段组拼
        foreach ($select as $column => $alias) {
            // Filter db keyword
            if (array_key_exists($column, $fieldSelect) && trim($column) != '*' && strpos($column, '.') === false) {
                // 判断是否为函数调用
                if (strpos($column, '(') || strpos($column, ')')) {
                    $column = sprintf('%s', $column);
                } else {
                    $column = sprintf('`%s`', $column);
                }
            }

            $statement .= $column;
            if ($alias !== null) {
                $statement .= sprintf(' AS `%s`', $alias);
            }
            $statement .= ', ';
        }

        //select组拼
        $statement = substr($statement, 0, -2);
        if (!empty($statement)) {
            $statement = 'SELECT ' . $statement;
        }

        return $statement;
    }
760963
public static function getSelectData()
    {
        $minutes = config('arcanesoft.blog.cache.tags.select-data', 5);

        /** @var  \Illuminate\Database\Eloquent\Collection  $categories */
        return cache()->remember(self::SELECT_CACHE_NAME, $minutes, function () {
            $withTranslations = Blog::instance()->isTranslatable();

            return self::all()->mapWithKeys(function (Tag $tag) use ($withTranslations) {
                return [
                    $tag->id => $withTranslations
                        ? implode(' / ', $tag->getTranslations('name'))
                        : $tag->name
                ];
            });
        })->toBase();
    }
561147
protected function select()
    {
        $colNames = array_keys($this->_cols);
        $colValues = DbTable::select(
            $this->db, $this->_tableName, $colNames, $this->id
        );

        $this->_cols = [];
        foreach ($colNames as $colName) {
            $this->_cols[$colName] = $colValues[$colName];
        }

        return $this->_cols["id"];
    }
247460
protected function getSelect()
    {
        $html = '<select>';

        if (is_array($this->window['all'])) {
            $html .= $this->getOptionLinks($this->window['all']);
        }

        $html .= '</select>';

        return $html;
    }
758627
public function getTable()
    {
        if ($this->_sql['from']) {
            $table = $this->_sql['from'];
        } else {
            $table = $this->table;
        }
        /**
         * 处理子查询问题
         * 子查询使用()包裹
         */
        if (strpos($table, ')') !== false && strpos($table, '(') !== false) {
            return $table;
        }
        $table = $this->prefix . $table;
        return $this->formatTable($table);
    }
275689
public function getTableField() {
        #不是全表名是添加表前缀
        if (!empty($this->fields)) {
            return $this->fields;
        }
        $name = C('sql', "table") . '.' . $this->table;
        #字段缓存
        if (!DEBUG && F($name, '[get]', 'temp/field')) {
            $data = F($name, '[get]', 'temp/field');
        } else {
            $sql = "show columns from " . $this->table;
            if (!$result = $this->query($sql)) {
                return FALSE;
            }
            $data = [];
            foreach ($result as $res) {
                $f['field']          = $res['Field'];
                $f['type']           = $res['Type'];
                $f['null']           = $res['Null'];
                $f['key']            = ($res['Key'] == "PRI" && $res['Extra']) || $res['Key'] == "PRI";
                $f['default']        = $res['Default'];
                $f['extra']          = $res['Extra'];
                $data[$res['Field']] = $f;
            }
            DEBUG || F($name, $data, 'temp/field');
        }
        return $this->fields = $data;
    }
1267628
public function index()
    {
        $searcher = Search::build(function (Searcher $searcher) {
            $searcher->like('user.name', 'name');
            $searcher->equal('method');
            $searcher->equal('ip');
        });

        $logs = (new OperationLog())->search($searcher)->orderBy('id', 'desc')->paginate(10);
        $header = '操作日志';
        $description = '列表';
        return view('admin::system.logs', compact('logs', 'header', 'description'));
    }
531894
private function getSelectQuery()
    {
        return 'SELECT '.(empty($this->parts['select']) ? '*' : implode(', ', $this->parts['select'])).
               ' FROM '.$this->getFromClause().
               (($this->parts['where'] !== null) ? ' WHERE '.$this->parts['where'] : null).
               (!empty($this->parts['group_by']) ? ' GROUP BY '.implode(', ', $this->parts['group_by']) : null).
               (($this->parts['having'] !== null) ? ' HAVING '.$this->parts['having'] : null).
               (!empty($this->parts['order_by']) ? ' ORDER BY '.implode(', ', $this->parts['order_by']) : null).
               (($this->parts['limit'] !== null) ? ' LIMIT '.$this->parts['limit'] : null).
               (($this->parts['offset'] !== null) ? ' OFFSET '.$this->parts['offset'] : null);
    }
565478
final public function select($select = "*") {
      $this->connection();
      if (func_num_args()>1)
         $select = func_get_args();
      else if(is_string($select)) {
         $select = [$select];
      }

      $select_tmp = [];
      foreach ($select as $value) {

         if ( $value===NULL )
            $select_tmp[] = ' NULL ';
         elseif ( gettype( $value )==='boolean' )
            $select_tmp[] = $value ? ' TRUE ' : ' FALSE ';
         elseif ($value instanceof \Closure) {
            $value(new \Daniia\Daniia());
            if (preg_match("/^CASE/", $_ENV['daniia_daniia']->case)) {
               $select_tmp[] = '( '.$_ENV['daniia_daniia']->case.' '.$_ENV['daniia_daniia']->when.' '.$_ENV['daniia_daniia']->else.' END )';
               $_ENV['daniia_daniia']->case = NULL;
            }
            else {
               $select_tmp[] = $_ENV['daniia_daniia']->get_sql();
               $_ENV['daniia_daniia'] = null;
            }
         }
         elseif ( in_array(strtolower(trim($value)), $this->columnsData, true) )
            $select_tmp[] = $value;
         else {
            $select_tmp[] = $value;
         }

      }

      $select = implode(",", $select_tmp);
      $this->select = str_replace("*", $select, $this->select);

      $this->find_first_data = $this->find_save_data = $this->find_delete_data = FALSE;

      $this->get_instance();
      return $this;
   }
936960
private function select() {
        $this->performed  = true;
        $this->resultSet  = [];
        $this->resultSets = [];
        $this->resultIdx  = 0;
        $this->maxIdx     = 0;
        $this->size       = 0;
        try {
            $this->checkDialect();
        } catch (DialectException $e) {
            $this->error = $e->getMessage();

            return;
        }
        //生成SQL
        if (!$this->sql) {
            $this->sql = $this->getSQL();
            if (!$this->sql) {
                $this->error       = 'can not generate the SQL';
                $this->errorSQL    = '';
                $this->errorValues = $this->values->__toString();

                return;
            }
            //重新生成SQL.
            $this->statement = null;
        }
        //生成prepare statement
        if (!$this->statement) {
            $this->prepareStatement();
        }
        //执行
        if ($this->statement) {
            try {
                if ($this->values) {
                    foreach ($this->values as $value) {
                        list ($name, $val, $type, $field, $rkey) = $value;
                        if ($this->whereData) {
                            $val = isset($this->whereData[ $rkey ]) ? $this->whereData[ $rkey ] : (isset($this->whereData[ $name ]) ? $this->whereData[ $name ] : $val);
                        }
                        if (!$this->statement->bindValue($name, $val, $type)) {
                            $this->errorSQL    = $this->sql;
                            $this->errorValues = $this->values->__toString();
                            $this->error       = 'can not bind the value ' . $val . '[' . $type . '] to the argument:' . $name . '(' . $field . ')';

                            return;
                        }
                    }
                }
                $rst = $this->statement->execute();
                QueryBuilder::addSqlCount();
                if ($rst) {
                    $this->resultSets = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
                    $this->size       = count($this->resultSets);
                    if ($this->size > 0) {
                        $this->maxIdx    = $this->size - 1;
                        $this->resultSet = $this->resultSets[0];
                    }
                } else {
                    $this->dumpSQL($this->statement);
                }
            } catch (\PDOException $e) {
                $this->exception   = $e;
                $this->error       = $e->getMessage();
                $this->errorSQL    = $this->sql;
                $this->errorValues = $this->values->__toString();
            }
        }
    }
569364
public function get_sql() : string {
		if ( empty( $this->columns_to_select ) ) {
			// this should be the default behavior
			$this->columns_to_select = [ '*' ];
		}

		$from = ' FROM ' . implode( ', ', $this->from ) . ' ';

		if ( ! empty( $this->joins ) ) {
			$from .= $this->joins;
		}

		$from  .= 'WHERE ' . $this->where_clause;
		$select = 'SELECT ' . implode( ', ', $this->columns_to_select ) . $from;

		if ( ! empty( $this->group_by ) ) {
			$select .= 'GROUP BY ' . implode( ', ', $this->group_by ) . ' ';
		}

		if ( $this->order_by !== '' ) {
			$select .= 'ORDER BY ' . $this->order_by . ' ';
		}

		$select .= 'LIMIT ' . $this->limit;

		if ( $this->offset !== '' ) {
			$select .= ' OFFSET ' . $this->offset;
		}

		return $select;
	}
843608
private function _read_sql()
    {
        // 可能是model::query('select')，直接接受SQL的查询操作
        if (!$this->query_sql) {
            $_table_name = $this->_get_table_name();

            $_join    = $this->join;
            $_where   = $this->where != '' ? ' WHERE ' . $this->where : '';
            $_orderby = $this->orderby != '' ? ' ORDER BY ' . $this->orderby : '';
            $_groupby = $this->groupby != '' ? ' GROUP BY ' . $this->groupby : '';
            $_limit   = $this->limit != '' ? ' LIMIT ' . $this->limit : '';
            $_having  = $this->having != '' ? ' HAVING ' . $this->having : '';

            $this->sql = 'SELECT ' . $this->field . ' FROM ' . $_table_name . $_join . $_where . $_groupby . $_having . $_orderby . $_limit;

            $this->_clear_var(); //清理使用过的变量
            return $this->sql;
        } else {
            $this->sql       = $this->query_sql;
            $this->query_sql = '';
            return $this->sql;
        }
    }
505206
protected function _getSelect() {
        $fields = $this->_entity->fields();

        switch ($this->_type) {
            case self::QUERY_SELECT :
                $this->_query .= 'SELECT ';

                $nFields = count($fields);
                $i = 0;

                //We add all fields to the select
                foreach ($fields as $value) {
                    //We mustn't add fields which don't exist in the SQL table
                    if ($value->foreign == null || in_array($value->foreign->type(), [ForeignKey::ONE_TO_ONE, ForeignKey::MANY_TO_ONE])) {
                        $this->_query .= $this->_entity->name() . '.' . $value->name . ' AS ' . $this->_entity->name() . '_' . $value->name;

                        if ($i < $nFields - 1) {
                            $this->_query .= ', ';
                        }
                    }
                    //To optimize the relation ONE TO MANY, we replace the join value by the number of element in this join
                    else if ($value->foreign != null && $value->foreign->type() == ForeignKey::ONE_TO_MANY) {
                        $currentEntity = $value->foreign->entity();
                        $currentField = $value->foreign->field();
                        $referenceEntity = $value->foreign->referenceEntity();
                        $referenceField = $value->foreign->referenceField();

                        $this->_query .= '(SELECT COUNT(*) FROM ' . $referenceEntity . ' WHERE ' . $referenceEntity . '.' . $referenceField . ' = ' . $currentEntity . '.' . $currentField . ') AS count_one_' . $this->_entity->name() . '_' . $value->name;

                        if ($i < $nFields - 1) {
                            $this->_query .= ', ';
                        }
                    }
                    //To optimize the relation MANY TO MANY, we replace the join value by the number of element in this join
                    else if ($value->foreign != null && $value->foreign->type() == ForeignKey::MANY_TO_MANY) {
                        $currentEntity = $value->foreign->entity();
                        $currentField = $this->_entity->primary();
                        $referenceEntity = $value->foreign->referenceEntity();
                        $referenceField = $value->foreign->referenceField();
                        $current = strtolower($currentEntity . $currentField);
                        $reference = strtolower($referenceEntity . $referenceField);
                        $table = [$current, $reference];
                        sort($table, SORT_STRING);
                        $table = ucfirst($table[0] . $table[1]);

                        $this->_query .= '(SELECT COUNT(*) FROM ' . $table . ' WHERE ' . $table . '.' . $currentEntity . '_' . $currentField . ' = ' . $currentEntity . '.' . $currentField . ') AS count_many_' . $this->_entity->name() . '_' . $value->name;

                        if ($i < $nFields - 1) {
                            $this->_query .= ', ';
                        }
                    }

                    $i++;
                }

                $this->_query = preg_replace('#^(.*)(, )$#isU', '$1', $this->_query);

                //if some fields have a relation one to one or many to one, we had a join
                foreach ($fields as $value) {
                    if ($value->foreign != null && in_array($value->foreign->type(), [ForeignKey::ONE_TO_ONE, ForeignKey::MANY_TO_ONE])) {
                        $this->_query .= ', ';

                        $class = $this->_getTableEntity($value->foreign->referenceEntity());

                        $fieldsRelation = $class->fields();
                        $nFieldsRelation = count($fieldsRelation);
                        $i = 0;

                        foreach ($fieldsRelation as $relation) {
                            if ($relation->foreign == null || in_array($relation->foreign->type(), [ForeignKey::ONE_TO_ONE, ForeignKey::MANY_TO_ONE])) {
                                $this->_query .= $value->name . '_' . $class->name() . '.' . $relation->name . ' AS ' . $value->name . '_' . $class->name() . '_' . $relation->name;

                                if ($i < $nFieldsRelation - 1) {
                                    $this->_query .= ', ';
                                }
                            }

                            $i++;
                        }

                        $this->_query = preg_replace('#^(.*)(, )$#isU', '$1', $this->_query);
                    }
                }
                break;

            case self::QUERY_DISTINCT :
                $primaryColumn = $this->_entity->name() . '.' . $this->_entity->fields()[$this->_entity->primary()]->name;

                if (preg_match('(' . $primaryColumn . ')', $this->_distinct)) {
                    $this->_query .= 'SELECT DISTINCT ' . $this->_distinct . ' ';
                }
                else {
                    $this->_query .= 'SELECT DISTINCT ' . $this->_distinct . ', ' . $primaryColumn . ' ';
                }
                break;

            case self::QUERY_COUNT :
                $this->_query .= 'SELECT COUNT(*) ';
                break;
        }

        $this->_query .= ' FROM ' . $this->_entity->name();

        /** If there are relations like one to one, many to one or many to many */
        foreach ($fields as $value) {
            if ($value->foreign != null && in_array($value->foreign->type(), [ForeignKey::ONE_TO_ONE, ForeignKey::MANY_TO_ONE])) {
                $entity = $value->foreign->entity();
                $field = $value->foreign->field();
                $referenceEntity = $value->foreign->referenceEntity();
                $referenceField = $value->foreign->referenceField();
                $this->join($value->foreign->join(), $referenceEntity, $entity . '.' . $field . ' = ' . $field . '_' . $referenceEntity . '.' . $referenceField, $field);
            }
            else if ($value->foreign != null && in_array($value->foreign->type(), [ForeignKey::MANY_TO_MANY])) {
                //We add here two join (relation table and table linked)
                $currentEntity = $value->foreign->entity();
                $currentField = $this->_entity->primary();
                $referenceEntity = $value->foreign->referenceEntity();
                $referenceField = $value->foreign->referenceField();

                $current = strtolower($currentEntity . $currentField);
                $reference = strtolower($referenceEntity . $referenceField);
                $table = [$current, $reference];
                sort($table, SORT_STRING);
                $table = ucfirst($table[0] . $table[1]);

                $this->join($value->foreign->join(), $table, $table . '.' . $this->_entity->name() . '_' . $currentField . ' = ' . $this->_entity->name() . '.' . $currentField);
                $this->join($value->foreign->join(), $value->foreign->referenceEntity(), $table . '.' . $referenceEntity . '_' . $referenceField . ' = ' . $referenceEntity . '.' . $referenceField);
            }
        }
    }
446785
public function getQuery()
    {
        $sql = $this->prepareSelectString();
        $sql .= $this->prepareJoinString();
        $sql .= $this->prepareWhereString();
        $sql .= $this->prepareGroupByString();
        $sql .= $this->prepareHavingString();
        $sql .= $this->prepareOrderByString();
        $sql .= $this->prepareLimitString();

        return $sql;
    }
1243347
protected function preprocessSelect()
    {
        // handle fields
        if (!isset($this->query['fields']) && !isset($this->query['distinct'])) {
            if (isset($this->query['count'])) {
                $this->query['fields'] = 'count(*)';
            } else {
                $this->query['fields'] = '*';
            }
        }
        
        if (isset($this->query['count']) || (is_string($this->query['fields'][0]) && strpos('count(', $this->query['fields'][0]) !== false)) {
            return ;
        }
        
        /**
         * 检查分页
         * start 作为初始偏移量
         * 
         * -- 解析出 pagesize
         * 1 如果设置了 limit, 从中解析出 offset|pagesize, offset 可能没有值
         * 2 如果未设置 limit 则检查 pagesize 或 num 选项, 得出 pagesize
         * 
         * -- 解析出 offset, 并得出最终 limit
         * 1 如果设置了 limit 且已包含offset, 则优先使用
         * 2 否则检查 page, 解析出 offset, 结合 pagesize 生成最终 limit
         * 3 否则使用已 解析的 start pagesize, 生成最终 limit
         */
        $start = isset($this->query['start']) && intval($this->query['start'][0])>0 ? intval($this->query['start'][0]) : 0;
        if (isset($this->query['limit'])) {     // 优先使用 limit
            if (is_numeric($this->query['limit'][0])) {
                $pagesize = $this->query['limit'][0];
            } else {
                if (!is_array($this->query['limit'][0])) $limitArr = explode(',', $this->query['limit'][0]);
                if (is_numeric($limitArr[0]) && is_numeric($limitArr[1])) {
                    $offset = $limitArr[0];
                    $pagesize = $limitArr[1];
                }
            }
        }
        if (!isset($pagesize) || ! $pagesize) {                  // limit 不存在则依次判断 pagesize, num
            if (isset($this->query['pagesize']) && intval($this->query['pagesize'][0])>0 ) {
                $pagesize   = intval($this->query['pagesize'][0]);
            } elseif (isset($this->query['num']) && intval($this->query['num'][0])>0 ) {
                $pagesize   = intval($this->query['num'][0]);
            }
        }
        
        if (isset($offset)) {
            $offset += $start;
            $limit      =  $offset . ',' . $pagesize;
        } elseif (isset($this->query['page'])) {
            $page       = intval($this->query['page'][0]) > 0 ? intval($this->query['page'][0]) : 1;
            // notice: $pagesize may be still null. 此时 pagesize 仍然可能为空，因为未设置或解析不正确
            $pagesize   = !empty($pagesize) ? $pagesize : 10;
            $offset     =  $start + $pagesize * ($page - 1);
            $limit      =  $offset . ',' . $pagesize;
        } elseif (isset($pagesize)) {
            $limit = $start . ',' . $pagesize;
        }
        if (isset($limit)) {
            $this->query->remove('limit')->set('limit', $limit);     // 强制重设
        }
    }
676509
private function select()
    {
        do {
            $mrc = curl_multi_exec($this->multi_handle, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active && $mrc == CURLM_OK) {
            if (curl_multi_select($this->multi_handle) !== -1) {
                do {
                    $mrc = curl_multi_exec($this->multi_handle, $active);
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            } else {
                return;
            }
        }

        while ($info = curl_multi_info_read($this->multi_handle)) {
            $ch = $info['handle'];
            $fd = (int)$ch;

            curl_multi_remove_handle($this->multi_handle, $ch);

            if (!isset($this->requests[$fd])) {
                return;
            }

            unset($this->requests[$fd]);
        }
    }
216325
protected static function makeSelect()
    {
        $self   = self::getInstance();
        $select = (!empty($self->optionSelect)) ? $self->optionSelect : "*";

        return "SELECT {$select} FROM {$self->table_name} ";
    }