MySQL 选择包含前导或尾随空格的字段

标签 mysql sql trim

我可以使用 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 all CHAR and VARCHAR 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 or VARCHAR 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/

相关文章:

php - 无法从数据库获取要链接的 URL

java - Hibernate HQL 转换 java.lang.ClassCastException : java. lang.Integer 无法转换为 java.lang.Long

PHP:从字符串的开头/结尾修剪单词或它的一部分

mysql - 如何获取不在表 "ids"中的 "service_gos"(Laravel)

MySQL配置自动截断十进制值

php - 为什么这个 PHP 脚本显示 ' Webpage Not Available '

sql - SQL Server 相当于 Oracle 的虚拟专用数据库吗?

sql - 如何用非相关子查询替换相关子查询?

javascript - jquery 追加在 IE 中不起作用在 FF 中工作正常

php - 从字符串 PHP 中删除第一个斜杠字符