如何在 MySQL CHAR 字段中存储 space 字符?

How can I store a space character in a MySQL CHAR field?

我有一个带有 CHAR(1) 字段的 MySQL Table。我在其中存储单个字符。有时我需要在该字段中存储一个 space,但 MySQL 不允许。我正在使用 MySQL v.5.6.22.

这会运行,但会存储一个空字段:

INSERT INTO
companies(name_char_0)
values(' ');

这个returns一个空值:

SELECT HEX(name_char_0)
FROM companies;

我没有遇到 VARCHAR(1) 字段的这个问题,但我有一系列这样的 CHAR 字段,因为查找和速度是个问题。我相信 VARCHAR(1) 字段的搜索速度总是比 CHAR(1) 字段慢。

在 CHAR 字段中,spaces 用于填充字段到其长度,然后 spaces 被剥离:

来自 https://dev.mysql.com/doc/refman/5.0/en/char.html

The length of a CHAR column is fixed to the length that you declare when you create the table. The length can be any value from 0 to 255. When CHAR values are stored, they are right-padded with spaces to the specified length. When CHAR values are retrieved, trailing spaces are removed.

如果只想保存 space,则不应使用 CHAR 类型。

如果您在 MySQL > 5.0.2 中使用 VARCHAR(1),您应该不会遇到此问题:

As of MySQL 5.0.3, trailing spaces are retained when values are stored and retrieved, in conformance with standard SQL. Before MySQL 5.0.3, trailing spaces are removed from values when they are stored into a VARCHAR column; this means that the spaces also are absent from retrieved values.