> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# optimize_limit_* 会话设置

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

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](/docs/zh/reference/system-tables/settings) 中查看，并由 [源代码](https://github.com/ClickHouse/ClickHouse/blob/master/src/Core/Settings.cpp) 自动生成。

<div id="optimize_limit_by_function_keys">
  ## optimize\_limit\_by\_function\_keys
</div>

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

<VersionHistory rows={[{"id": "row-1","items": [{"label": "26.6"},{"label": "1"},{"label": "新增设置：消除 LIMIT BY 键中可由其他 LIMIT BY 键推导出的函数键。"}]}]} />

消除 LIMIT BY 部分中可由其他键推导出的函数键。

示例：`LIMIT 5 BY x, f(x)` 会变为 `LIMIT 5 BY x`。

<div id="optimize_limit_by_in_order">
  ## optimize\_limit\_by\_in\_order
</div>

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

<VersionHistory rows={[{"id": "row-1","items": [{"label": "26.6"},{"label": "1"},{"label": "新增设置：当 `BY` 列是表排序键的前缀时，优化 `LIMIT BY` 查询。"}]}]} />

当 `<cols>` (顺序不限) 构成表排序键的前缀时，或者在 `WHERE col = const` 固定前导列后能够构成此前缀时，可优化 `SELECT ... LIMIT N BY <cols>` 查询。启用后，源端会按主键顺序读取数据，因此在每个流内，`BY` 列值相同的行会相邻到达。当数据以单个已排序流到达时，`LIMIT BY` 会以流式模式进行过滤，只需 O(1) 内存，而无需为已见到的每种不同 `BY` 列组合构建哈希表。当已排序数据通过多个流到达，且相同的 `BY` 值可能出现在多个流中时，系统会先以流式模式对每个流进行预过滤，将每个分组最多保留 `LIMIT + OFFSET` 行；然后再合并这些流，并通过最终基于哈希的 `LIMIT BY` 对跨多个流的分组进行去重。最后这一轮仍会为 `BY` 列的每种不同组合保留一个条目，但只处理预过滤后的行。
