跳至主要内容
跳至主要内容

FixedString(N)

一个固定长度的字符串,长度为 N 字节(既不是字符也不是码点)。

要声明一个 FixedString 类型的列,请使用以下语法

<column_name> FixedString(N)

其中 N 是一个自然数。

当数据长度恰好为 N 字节时,FixedString 类型效率很高。在所有其他情况下,它可能会降低效率。

可以高效存储在 FixedString 类型列中的值的示例

  • IP 地址的二进制表示形式(IPv6 的 FixedString(16))。
  • 语言代码(ru_RU、en_US ...)。
  • 货币代码(USD、RUB ...)。
  • 哈希的二进制表示形式(MD5 的 FixedString(16),SHA256 的 FixedString(32))。

要存储 UUID 值,请使用 UUID 数据类型。

在插入数据时,ClickHouse

  • 如果字符串少于 N 个字节,则用空字节进行补齐。
  • 如果字符串多于 N 个字节,则抛出 Too large value for FixedString(N) 异常。

让我们考虑一个包含单个 FixedString(2) 列的表



INSERT INTO FixedStringTable VALUES ('a'), ('ab'), ('');
SELECT
    name,
    toTypeName(name),
    length(name),
    empty(name)
FROM FixedStringTable;
┌─name─┬─toTypeName(name)─┬─length(name)─┬─empty(name)─┐
│ a    │ FixedString(2)   │            2 │           0 │
│ ab   │ FixedString(2)   │            2 │           0 │
│      │ FixedString(2)   │            2 │           1 │
└──────┴──────────────────┴──────────────┴─────────────┘

请注意,FixedString(N) 值的长度是恒定的。即使 FixedString(N) 值仅填充了空字节,length 函数也会返回 N,但 empty 函数在这种情况下返回 1

使用 WHERE 子句选择数据,根据条件的指定方式返回不同的结果

  • 如果使用相等运算符 ===equals 函数,ClickHouse 不会\0 字符考虑在内,即查询 SELECT * FROM FixedStringTable WHERE name = 'a';SELECT * FROM FixedStringTable WHERE name = 'a\0'; 返回相同的结果。
  • 如果使用 LIKE 子句,ClickHouse \0 字符考虑在内,因此可能需要在筛选条件中显式指定 \0 字符。
SELECT name
FROM FixedStringTable
WHERE name = 'a'
FORMAT JSONStringsEachRow

{"name":"a\u0000"}


SELECT name
FROM FixedStringTable
WHERE name = 'a\0'
FORMAT JSONStringsEachRow

{"name":"a\u0000"}


SELECT name
FROM FixedStringTable
WHERE name = 'a'
FORMAT JSONStringsEachRow

Query id: c32cec28-bb9e-4650-86ce-d74a1694d79e

{"name":"a\u0000"}


SELECT name
FROM FixedStringTable
WHERE name LIKE 'a'
FORMAT JSONStringsEachRow

0 rows in set.


SELECT name
FROM FixedStringTable
WHERE name LIKE 'a\0'
FORMAT JSONStringsEachRow

{"name":"a\u0000"}
    © . This site is unofficial and not affiliated with ClickHouse, Inc.