> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-detect-table-modification.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# optimize_trivial_* 会话设置

> ClickHouse 中 optimize_trivial_* 自动生成分组的会话设置。

export const BetaBadge = ({link, galaxyTrack, galaxyEvent}) => {
  if (link) {
    return <a href={link} target="_blank" rel="noopener noreferrer" className="betaBadge" onClick={galaxyTrack && galaxyEvent ? galaxyOnClick(galaxyEvent) : undefined}>
                <span>Beta</span>
            </a>;
  }
  return <a href="https://clickhouse.com/docs/reference/settings/beta-and-experimental-features#beta-features" className="betaBadge">
            <span>Beta 版功能</span>
        </a>;
};

export const VersionHistory = ({rows = []}) => {
  if (rows.length === 0) {
    return null;
  }
  const headers = ["版本", "默认值", "注释"];
  const border = "1px solid rgba(128, 128, 128, 0.3)";
  const cell = {
    border,
    padding: "0.25rem 0.5rem",
    textAlign: "start",
    verticalAlign: "top"
  };
  return <details className="not-prose" style={{
    border,
    borderRadius: "0.5rem",
    margin: "0.5rem 0",
    padding: "0.5rem 0.75rem",
    fontSize: "0.8125rem",
    lineHeight: "1.125rem"
  }}>
      <summary style={{
    cursor: "pointer",
    fontWeight: 600,
    opacity: 0.72
  }}>
        版本历史
      </summary>
      <table style={{
    borderCollapse: "collapse",
    width: "100%",
    margin: "0.5rem 0 0"
  }}>
        <thead>
          <tr>
            {headers.map(header => <th key={header} style={{
    ...cell,
    fontWeight: 600,
    opacity: 0.72
  }}>
                {header}
              </th>)}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, row_index) => <tr key={row.id ?? row_index}>
              {(row.items ?? []).map((item, item_index) => <td key={item_index} style={{
    ...cell,
    overflowWrap: "anywhere"
  }}>
                  {item?.label}
                </td>)}
            </tr>)}
        </tbody>
      </table>
    </details>;
};

export const SettingsInfoBlock = ({type, default_value, changeable_without_restart}) => {
  return <div className="not-prose" style={{
    display: "flex",
    flexWrap: "wrap",
    alignItems: "baseline",
    columnGap: "0.5rem",
    rowGap: "0.125rem",
    margin: "0.375rem 0",
    fontSize: "0.8125rem",
    lineHeight: "1.125rem"
  }}>
      <div style={{
    fontWeight: 600,
    opacity: 0.72
  }}>类型</div>
      <div style={{
    overflowWrap: "anywhere"
  }}>{type}</div>
      <div style={{
    fontWeight: 600,
    opacity: 0.72,
    marginInlineStart: "0.5rem"
  }}>默认值</div>
      <div style={{
    overflowWrap: "anywhere"
  }}>{default_value}</div>
      {changeable_without_restart && <div style={{
    fontWeight: 600,
    opacity: 0.72,
    marginInlineStart: "0.5rem"
  }}>
          无需重启即可更改
        </div>}
      {changeable_without_restart && <div style={{
    overflowWrap: "anywhere"
  }}>
          {changeable_without_restart}
        </div>}
    </div>;
};

这些设置可在 [system.settings](/zh/reference/system-tables/settings) 中查看，且由 [源文件](https://github.com/ClickHouse/ClickHouse/blob/master/src/Core/Settings.cpp) 自动生成。

<div id="optimize_trivial_approximate_count_query">
  ## optimize\_trivial\_approximate\_count\_query
</div>

<SettingsInfoBlock type="Bool" default_value="0" />

对于支持此类估算的存储 (例如 EmbeddedRocksDB) ，在简单 count 优化中使用近似值。

可能的值：

* 0 — 禁用优化。
  * 1 — 启用优化。

<div id="optimize_trivial_count_query">
  ## optimize\_trivial\_count\_query
</div>

<SettingsInfoBlock type="Bool" default_value="1" />

启用或禁用对简单查询 `SELECT count() FROM table` 的优化，该优化会使用 MergeTree 的元数据。如果需要使用行级安全，请禁用此设置。

可能的值：

* 0 — 禁用优化。
  * 1 — 启用优化。

另请参阅：

* [optimize\_functions\_to\_subcolumns](/zh/reference/settings/session-settings/optimize#optimize_functions_to_subcolumns)

<div id="optimize_trivial_count_with_sparsity_filter">
  ## optimize\_trivial\_count\_with\_sparsity\_filter
</div>

<BetaBadge />

<SettingsInfoBlock type="Bool" default_value="1" />

<VersionHistory rows={[{"id": "row-1","items": [{"label": "26.8"},{"label": "1"},{"label": "升级为 Beta 并默认启用：当 `<pred>` 将行划分为默认值和非默认值时，使用持久化存储的每列 `num_defaults` \/ `num_rows` 计数器直接返回 `SELECT count() FROM t WHERE <pred>` 的结果。需要 MergeTree 设置 `compute_exact_num_defaults_for_sparse_columns`（现也默认启用）。"}]}, {"id": "row-2","items": [{"label": "26.7"},{"label": "0"},{"label": "新增（实验性）设置：当 `<pred>` 可将行精确划分为 `col` 的默认值与非默认值时，可利用记录在 `serialization.json` 中的每列 `num_defaults` \/ `num_rows` 为 `SELECT count() FROM t WHERE <pred>` 直接返回结果。"}]}]} />

将 [optimize\_trivial\_count\_query](/zh/reference/settings/session-settings/optimize-trivial#optimize_trivial_count_query) 优化扩展到
形如 `SELECT count() FROM t WHERE col <op> const` 的
查询，其中 `<op> const`
必须能够将行精确划分为 `col` 的默认值和非默认值。这样，计数结果即可
直接根据 MergeTree 已记录在 `serialization.json` 中的每列 `num_defaults` / `num_rows`
计数器返回，无需扫描数据。

可识别的模式：

* `col = default(col)` / `col != default(col)`，适用于 `Int*` / `UInt*`、`String` /
  `FixedString`、`Date` / `DateTime` / `DateTime64`、`Decimal*`、`UUID`、`IPv4` / `IPv6`。
* `Nullable` 列上的 `IS NULL` / `IS NOT NULL`。
* `String` 列上的 `empty(col)` / `notEmpty(col)`。
* `Bool` 列上的 `col = true` / `col != true`。
* 无符号整数列上的 `col > 0`、`col >= 1`、`col < 1`、`col <= 0`。
* `Int*`、`UInt*`、`Bool` 列上直接使用 `col` / `NOT col` (真值判断)。

相等模式不适用于 `Float*`、`Enum*`、`Nullable`、`LowCardinality`，
或复合类型 (`Tuple`、`Array`、`Map`、...) —— 对于这些类型，计数仍会走
常规扫描路径。

要使其生效，每个 part 的 `num_defaults` 计数器必须是精确的。请在插入和合并之前，
先在目标表上启用 MergeTree
表设置 `compute_exact_num_defaults_for_sparse_columns`。未启用该设置时写入的 parts
会被静默排除在此重写之外，因此仅启用 `optimize_trivial_count_with_sparsity_filter`
还不够。

对于 `Nullable` 列上的 `IS NULL` / `IS NOT NULL` 模式，该列还必须
在 `serialization.json` 中具有 `num_defaults` 条目，而这只会在插入 /
合并时将 MergeTree
表设置 `nullable_serialization_version` 设为 `allow_sparse` 时发生。使用默认值 `basic` 时，`Nullable` 列不会有每列条目，因此
该优化会静默失效。

可选值：

* 0 — 优化已禁用。
  * 1 — 优化已启用。

另请参见：

* [optimize\_trivial\_count\_query](/zh/reference/settings/session-settings/optimize-trivial#optimize_trivial_count_query)

<div id="optimize_trivial_group_by_limit_query">
  ## optimize\_trivial\_group\_by\_limit\_query
</div>

<SettingsInfoBlock type="Bool" default_value="1" />

<VersionHistory rows={[{"id": "row-1","items": [{"label": "26.5"},{"label": "1"},{"label": "用于将 `SELECT key_expr FROM t GROUP BY key_expr LIMIT n` 查询的聚合最多限制为 LIMIT 个不同键的新设置。"}]}]} />

通过设置 `max_rows_to_group_by = n + offset` 和 `group_by_overflow_mode = 'any'`，启用或禁用对简单查询 `SELECT key_expr FROM table GROUP BY key_expr LIMIT n` 的优化 (要求投影中没有聚合函数、窗口函数或 `arrayJoin`，且不存在 `HAVING`/`ORDER BY`/`QUALIFY`/`LIMIT BY`/`DISTINCT`/窗口子句，也没有 `GROUP BY` 修饰符) 。当产生 `n + offset` 个不同键后，聚合会停止。

当用户显式将 `group_by_overflow_mode` 设置为非 `any` 值时 (以保留其显式指定的 `throw`/`break` 行为) ，以及当用户已设置了更严格的 `max_rows_to_group_by` 时 (此时该优化会成为空操作) ，将不会应用此优化。

可选值：

* 0 — 禁用该优化。
* 1 — 启用该优化。

<div id="optimize_trivial_insert_select">
  ## optimize\_trivial\_insert\_select
</div>

<SettingsInfoBlock type="Bool" default_value="0" />

<VersionHistory rows={[{"id": "row-1","items": [{"label": "24.7"},{"label": "0"},{"label": "在许多情况下，此优化并无意义。"}]}]} />

对简单的 'INSERT INTO table SELECT ... FROM TABLES' 查询进行优化

<div id="optimize_trivial_view_pushdown_to_distributed">
  ## optimize\_trivial\_view\_pushdown\_to\_distributed
</div>

<SettingsInfoBlock type="Bool" default_value="1" />

<VersionHistory rows={[{"id": "row-1","items": [{"label": "26.8"},{"label": "1"},{"label": "新增设置：对于基于 Distributed 表的简单视图，将完整的外层查询下推到分片。"}]}]} />

启用后，对于基于 [Distributed](/zh/reference/engines/table-engines/special/distributed) 表的视图，若其 `SELECT` 列表仅包含列引用、`*`
或表达式 (但不包含窗口函数或标量子查询) ，且不涉及聚合、分组、排序或联接，则完整的外层查询会被下推到
各个分片。这样，分片可在本地应用视图的过滤器和表达式，从而减少网络传输的数据量。

可能的值：

* 0 — 该优化已禁用；基于 `Distributed` 表的视图始终在协调器上执行。
* 1 — 该优化已启用。
