我可以使用 MySQL TRIM()
方法通过 UPDATE
清理包含前导或尾随空格的字段,如下所示:
UPDATE Foo SET field = TRIM(field);
我想在运行之前实际查看这将影响的字段。我试过了,但返回 0 个结果:
SELECT * FROM Foo WHERE field != TRIM(field);
这似乎应该有效,但实际上没有。
谁有解决办法?另外,好奇为什么这不起作用......
最佳答案
如 The CHAR
and VARCHAR
Types 中所述:
All MySQL collations are of type
PADSPACE
. This means that allCHAR
andVARCHAR
values in MySQL are compared without regard to any trailing spaces.
在 LIKE
的定义中运算符(operator),手册指出:
In particular, trailing spaces are significant, which is not true for
CHAR
orVARCHAR
comparisons performed with the=
operator:
如 this answer 中所述:
This behavior is specified in SQL-92 and SQL:2008. For the purposes of comparison, the shorter string is padded to the length of the longer string.
From the draft (8.2 <comparison predicate>):
If the length in characters of X is not equal to the length in characters of Y, then the shorter string is effectively replaced, for the purposes of comparison, with a copy of itself that has been extended to the length of the longer string by concatenation on the right of one or more pad characters, where the pad character is chosen based on CS. If CS has the NO PAD characteristic, then the pad character is an implementation-dependent character different from any character in the character set of X and Y that collates less than any string under CS. Otherwise, the pad character is a <space>.
一种解决方案:
SELECT * FROM Foo WHERE CHAR_LENGTH(field) != CHAR_LENGTH(TRIM(field))
关于MySQL 选择包含前导或尾随空格的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16724574/